请你看我这个C++程序#include <iostream> #include <cstdlib> #include… · The Chat Archive
请你看我这个C++程序#include
#include
#include
#include
// 模拟抽卡函数
bool simulatePull(bool& guaranteed, int& pullCount, int poolType) {
double baseRate = 0.006;
int pityStart = (poolType == 1) ? 73 : 63;
int hardPity = (poolType == 1) ? 90 : 80;
double rateIncrease = 0.062;
code Copy code
double pullRate = baseRate;
if (pullCount >= pityStart) {
pullRate += (pullCount - pityStart) * rateIncrease;
}
bool gotGold = (pullCount >= hardPity) || (static_cast<double>(std::rand()) / RAND_MAX) < pullRate;
if (gotGold) {
pullCount = 0;
if (guaranteed || (static_cast<double>(std::rand()) / RAND_MAX) < ((poolType == 1) ? 0.5 : 0.25)) {
guaranteed = false;
return true; // Featured item
} else {
guaranteed = true;
return false; // Non-featured item
}
} else {
pullCount += 1;
}
return false;
}
// 计算平均抽数
double calculateAveragePulls(int roleCount, int weaponCount) {
int totalPulls = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = false, guaranteedWeapon = false;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = 0, weaponPullCount = 0;
code Copy code
while (roleObtained < roleCount || weaponObtained < weaponCount) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2)) {
weaponObtained++;
}
pulls++;
}
}
totalPulls += pulls;
}
return static_cast<double>(totalPulls) / 10000.0;
}
// 模拟道具数量下的成功率
double simulateWithItems(int roleCount, int weaponCount, int items, int initialRolePulls, int initialWeaponPulls, bool majorPity) {
int successfulSimulations = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = false, guaranteedWeapon = false;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = initialRolePulls, weaponPullCount = initialWeaponPulls;
code Copy code
while (pulls < items) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount && pulls < items) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2)) {
weaponObtained++;
}
pulls++;
}
if (roleObtained >= roleCount && weaponObtained >= weaponCount) {
successfulSimulations++;
break;
}
}
}
return static_cast<double>(successfulSimulations) / 10000.0;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " ..." << std::endl;
return 1;
}
code Copy code
std::srand(std::time(0)); // 设置随机种子
std::string function = argv[1];
if (function == "-average") {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " -average <roleCount> <weaponCount>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
double averagePulls = calculateAveragePulls(roleCount, weaponCount);
std::cout << averagePulls << std::endl;
} else if (function == "-simulate") {
if (argc < 8) {
std::cerr << "Usage: " << argv[0] << " -simulate <roleCount> <weaponCount> <items> <initialRolePulls> <initialWeaponPulls> <majorPity>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int items = std::stoi(argv[4]);
int initialRolePulls = std::stoi(argv[5]);
int initialWeaponPulls = std::stoi(argv[6]);
bool majorPity = std::stoi(argv[7]);
double successRate = simulateWithItems(roleCount, weaponCount, items, initialRolePulls, initialWeaponPulls, majorPity);
std::cout << successRate * 100.0 << "%" << std::endl;
} else {
std::cerr << "Invalid function specified." << std::endl;
return 1;
}
return 0;
}
Show full message · 132 lines Assistant2024-11-06 11:37 UTC Copy response
你的C++程序实现了一个模拟抽卡系统,主要功能包括计算平均抽数和模拟道具数量下的成功率。这是一个很有趣的程序,可以帮助用户估算游戏中的抽卡概率。
下面是对程序的简要说明和一些可能的改进建议:
程序说明
simulatePull :
这是一个模拟单次抽卡的函数。它根据当前抽数进行概率计算,并判断是否获得抽卡池中的金色物品。
考虑了保底机制,包括第一次保底和大保底。
calculateAveragePulls :
计算为得到指定数量的角色和武器所需的平均抽数。
模拟了10000次,以获得抽卡的平均值。
simulateWithItems :
模拟在一定数量道具限制下的成功率。
同样进行了10000次模拟以获得统计数据。
main函数 :
程序入口,根据命令行参数执行计算平均抽数或模拟道具模式下的成功率。
可能的改进和建议
随机种子 :
使用std::srand(std::time(0))设置随机种子会使得每次程序运行时产生不同的结果。如果希望程序的行为可重复,可以考虑允许用户指定种子或使用固定的种子。
参数验证 :
可以加强对参数的验证,确保用户输入的是有效的数字和合理的值。
代码优化 :
抽卡逻辑存在重复部分,可以进一步提取和函数化以减少重复代码。
在计算成功率和平均抽数时,可以考虑使用多线程技术进行加速,特别是在进行大量模拟的情况下。
输出友好性 :
可以在输出中加入更多信息,如模拟次数、结果的标准差等,帮助用户更全面地了解模拟的数据。
用户交互 :
提供更多的交互指令或功能,例如输出不同情况下的详细模拟结果。
此程序已具备基础功能,如有进一步需求,可以按以上建议进行改进和扩展。希望这些建议对你有帮助!
请你帮我改进,我发现代码有些问题,抽卡规则:角色池:1-73抽,每抽0.6%出金,74-89抽,每抽0.6%+(k-73)*6.2%出金,如果89抽还没出,则90抽必出,出金有50%获得限定,如果上一次出金是非限定,则这一次必定是限定。武器池:1-63抽,每抽0.6%出金,64-79抽,每抽0.6%+(k-63)*6.2%出金,如果79抽还没出,则80抽必出,出金有75%获得限定,如果上一次出金是非限定,则这一次必定是限定。出限定之后刷新这个保底机制,继续改成50%/75%,且每次出金刷新抽数到0,软件一共安排2种接口,插到python程序里,python需要有2个功能,先创建一个窗口,功能1是让玩家输入他需要的限定角色和武器数,然后模拟器反复抽卡,一直到出满足这个条件的数量,重复10000次,记录平均抽数反馈给python,功能2是,让玩家输入他需要的限定角色和武器数以及他现有的道具数量和两个池子已经有记录的抽数,以及勾选是否大保底(大保底就是第一个金必定是限定,然后刷新,已经记录的抽数就是玩家以及投入的抽数,模拟器将从n+1开始模拟,直到出金后刷新),模拟器按照先抽角色,限定角色数量到达玩家要求后抽武器的顺序抽卡,直到抽完玩家所有的道具,重复10000次,记录能达到玩家要求的抽卡次数的比例。python是这样的import sys
import os
import json
import logging
import requests
import pickle
from datetime import datetime
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QMessageBox, QScrollArea, QFrame, QInputDialog,
QGridLayout, QGraphicsDropShadowEffect, QDesktopWidget)
from PyQt5.QtGui import QFont, QIcon, QPixmap, QFontDatabase, QColor, QBrush, QPalette
from PyQt5.QtCore import Qt, QSize
import subprocess
import webbrowser
定义日志路径和配置信息
SAVE_DIR = "./saves/players"
CONFIG_DIR = "./config/software/"
ELEMENT_COLOR_FILE = os.path.join(CONFIG_DIR, "elementcolor.json")
PATHS_MAPPING_FILE = os.path.join(CONFIG_DIR, "pathsmapping.json")
设置日志记录
log_dir = "./logs/"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_filename = f"srtool_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(os.path.join(log_dir, log_filename), encoding='utf-8')
])
加载元素颜色配置
def load_element_colors():
if not os.path.exists(ELEMENT_COLOR_FILE):
logging.error(f"Element color configuration file not found: {ELEMENT_COLOR_FILE}")
return {}
with open(ELEMENT_COLOR_FILE, 'r', encoding='utf-8') as f:
element_colors = json.load(f)
logging.debug(f"Loaded element colors: {element_colors}")
return element_colors
加载命途映射配置
def load_paths_mapping():
if not os.path.exists(PATHS_MAPPING_FILE):
logging.error(f"Paths mapping configuration file not found: {PATHS_MAPPING_FILE}")
return {}
with open(PATHS_MAPPING_FILE, 'r', encoding='utf-8') as f:
paths_mapping = json.load(f)
logging.debug(f"Loaded paths mapping: {paths_mapping}")
return paths_mapping
角色详细信息窗口类
class CharacterDetailWindow(QWidget):
def init (self, character, element_colors, paths_mapping):
super().init ()
self.character = character
self.element_colors = element_colors
self.paths_mapping = paths_mapping
self.initUI()
Show full message · 504 lines Assistant2024-11-06 11:41 UTC Copy response
为了满足需求,我将帮助你修改C++程序,更新实现逻辑以匹配新的抽卡规则。同时,在Python程序中实现与C++程序的交互,以便通过点击按钮执行模拟并获取结果。
C++程序
首先,根据新的指引,我将更新C++代码,以符合角色池和武器池的抽卡规则:
两个池子都有大保底选项,且两个卡池抽数和保底都不互通,要分别模拟!
Assistant2024-11-06 11:43 UTC Copy response
基于你的新要求,我将更新C++和Python代码,以分别模拟角色池和武器池,并在两个池子中独立处理大保底和抽数。
更新的C++程序
以下是更新后的C++代码,确保每个池子(角色/武器)分别模拟,并考虑各自的保底规则:
Assistant2024-11-06 11:47 UTC Copy response
当然,我将完整地提供C++和Python代码,只修改需要更新的部分,确保你所需的功能得到添加,同时其他代码保持不变。
C++ Code (ratecalc.cpp)
Assistant2024-11-06 11:51 UTC Copy response
好的,以下是完整的Python代码,包括了你原始的代码和新添加的功能,以便直接复制并使用。这个代码将实现绑定新的按钮功能以处理抽卡模拟。
Show full message · 555 lines 你的cpp算法是否有些问题,武器池计算的不对,此外-average增加功能:每抽有10%出4星,如果前9抽没有4星,第10抽必定出1个4星,但5星比4星优先级高,如果这里恰好roll到5星,则4星顺延至下一个。最后输出3个数值,期望抽数 四星数 星琼数(期望抽数向上取整)x160,此外python代码需要做一个大ui窗口而不是一堆对话框,而且python只做了第2个功能,没看到第一个
Assistant2024-11-06 11:58 UTC Copy response
好的,让我们来调整C++代码以修正算法问题并满足新的输出要求。然后,我将为Python程序设计一个更大、更集成的UI,以处理两个功能。
C++ Code Update
首先,让我们修正武器池的概率计算,并增加处理4星结果计算的逻辑:
Show full message · 371 lines 如果这里恰好roll到5星,则4星顺延至下一个没体现,此外功能二没了
Assistant2024-11-06 12:00 UTC Copy response
抱歉,我会调整C++代码来确保4星的顺延规则得以正确实现,并更新Python代码以确保两个功能都被正确实现。以下是调整后的代码:
C++ Code Update
我们需要在simulatePull函数中处理4星顺延逻辑,并在主逻辑中计算两个功能所需的结果。
Show full message · 343 lines 这不够完整,基于一开始五百多行的代码给我输出,cpp不需要再输出一次
Assistant2024-11-06 12:01 UTC Copy response
我将补充完整的Python代码,以包括你最初提到的所有功能,包括使用更新后的UI实现的两个功能。
Show full message · 260 lines 先改cpp代码 武器池还是不对,我看你似乎和角色池混用了
Assistant2024-11-06 12:04 UTC Copy response
让我重新仔细检查并修正C++代码,确保武器池的逻辑与角色池分开处理,并符合你的需求。
在武器池和角色池中,我们应该有独立的处理机制。以下代码将修正这一问题:
删除显示4星的功能 武器池子还是不对,注意是出金75%出限定,如果没出第二次100%,(static_cast(std::rand()) / RAND_MAX) < ((poolType == 1) ? 0.5 : 0.75))为什么只有一个定义
Assistant2024-11-06 12:08 UTC Copy response
让我们来修正武器池的处理逻辑。对于武器池,当第一次出金未获得限定时,下次出金则保证为限定。同样道理,角色池也是如此机制。我们将确保武器池的概率处理正确,并清晰地区分角色池和武器池的出金概率。
以下是更新后的C++代码:
Assistant2024-11-06 12:09 UTC Copy response
好的,让我们将角色池和武器池的逻辑完全拆开,以确保两个池子的抽取规则独立处理。
以下是更新后的C++代码:
Copy first response
Not yet included in a published release.
def initUI(self):
self.setWindowTitle(f"{self.character['name']} - Detailed Information")
self.showMaximized()
# 设置窗口的背景图片
self.set_background()
# 创建主布局
main_layout = QVBoxLayout(self)
main_layout.setContentsMargins(0, 0, 0, 0)
# 创建一个QScrollArea
scroll_area = QScrollArea(self)
scroll_area.setWidgetResizable(True)
scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
# 创建一个容器小部件,并将其放置在scroll area中
container = QWidget()
scroll_area.setWidget(container)
# 在容器小部件上设置布局
layout = QVBoxLayout(container)
layout.setContentsMargins(50, 50, 50, 50)
# 添加角色立绘
splashart_path = f"image/splashart/{self.character['id']}.png"
splashart_pixmap = QPixmap(splashart_path).scaled(768, 768, Qt.KeepAspectRatio, Qt.SmoothTransformation)
splashart_label = QLabel(self)
splashart_label.setPixmap(splashart_pixmap)
# 添加命途符号
path_name = self.character['path']['name'].lower()
path_icon_key = self.paths_mapping.get(path_name, None)
if path_icon_key:
path_icon_path = f"image/path/{path_icon_key}.png"
path_pixmap = QPixmap(path_icon_path).scaled(128, 128, Qt.KeepAspectRatio, Qt.SmoothTransformation)
path_icon_label = QLabel(splashart_label)
path_icon_label.setPixmap(path_pixmap)
path_icon_label.move(10, 10)
layout.addWidget(splashart_label, alignment=Qt.AlignLeft | Qt.AlignTop)
# 将scroll_area加入主布局
main_layout.addWidget(scroll_area)
def set_background(self):
# 设置固定背景图片
palette = self.palette()
background_pixmap = QPixmap("image/gui/background.jpeg").scaled(self.size(), Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)
palette.setBrush(QPalette.Window, QBrush(background_pixmap))
self.setPalette(palette)
def resizeEvent(self, event):
# 调整背景图片大小以覆盖整个窗口
self.set_background()
super().resizeEvent(event)
主应用程序类 class HSRToolApp(QWidget):
def init (self):
super().init ()
self.current_data = None
self.current_player = None
self.element_colors = load_element_colors()
self.paths_mapping = load_paths_mapping()
self.detail_windows = [] # 存储角色详细信息窗口的列表
self.initUI()
code Copy code
def initUI(self):
self.setWindowTitle("HSR Toolkit")
self.setWindowIcon(QIcon("image/gui/icon.ico"))
self.setGeometry(0, 0, 800, 600)
self.showMaximized()
layout = QHBoxLayout(self)
self.left_frame = QFrame()
self.left_layout = QVBoxLayout()
self.left_layout.setAlignment(Qt.AlignTop)
self.add_player_button = QPushButton("添加玩家数据")
self.add_player_button.setIcon(QIcon("image/gui/add.svg"))
self.add_player_button.setIconSize(QSize(24, 24))
self.add_player_button.setFixedWidth(600)
self.add_player_button.setStyleSheet("""
QPushButton {
border: 2px solid black;
border-radius: 10px;
color: gray;
background-color: white;
padding: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: lightblue;
color: black;
}
""")
self.add_player_button.setToolTip("点击添加玩家数据")
self.add_player_button.clicked.connect(self.prompt_for_uid)
self.left_layout.addWidget(self.add_player_button, alignment=Qt.AlignTop)
self.player_buttons_frame = QVBoxLayout()
self.player_buttons_frame.setAlignment(Qt.AlignTop)
self.left_layout.addLayout(self.player_buttons_frame)
self.cmd_button = QPushButton()
self.gold_ticket_button = QPushButton()
self.silver_ticket_button = QPushButton()
cmd_pixmap = QPixmap("image/gui/cmd.png").scaled(80, 80, Qt.KeepAspectRatio)
gold_ticket_pixmap = QPixmap("image/gui/GoldTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
silver_ticket_pixmap = QPixmap("image/gui/SilverTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
self.cmd_button.setIcon(QIcon(cmd_pixmap))
self.cmd_button.setIconSize(cmd_pixmap.size())
self.cmd_button.setFixedSize(80, 80)
self.gold_ticket_button.setIcon(QIcon(gold_ticket_pixmap))
self.gold_ticket_button.setIconSize(gold_ticket_pixmap.size())
self.gold_ticket_button.setFixedSize(80, 80)
self.silver_ticket_button.setIcon(QIcon(silver_ticket_pixmap))
self.silver_ticket_button.setIconSize(silver_ticket_pixmap.size())
self.silver_ticket_button.setFixedSize(80, 80)
self.cmd_button.clicked.connect(self.open_cmd)
self.gold_ticket_button.clicked.connect(self.open_ticket_simulator)
self.silver_ticket_button.clicked.connect(self.run_rate_calculator)
bottom_layout = QHBoxLayout()
bottom_layout.addWidget(self.cmd_button)
bottom_layout.addWidget(self.gold_ticket_button)
bottom_layout.addWidget(self.silver_ticket_button)
self.left_layout.addStretch()
self.left_layout.addLayout(bottom_layout)
self.left_frame.setLayout(self.left_layout)
layout.addWidget(self.left_frame, stretch=22)
self.right_frame = QFrame()
self.right_layout = QVBoxLayout()
self.right_layout.setAlignment(Qt.AlignTop)
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_widget = QWidget()
self.scroll_layout = QVBoxLayout()
self.scroll_layout.setAlignment(Qt.AlignTop)
self.scroll_widget.setLayout(self.scroll_layout)
self.scroll_area.setWidget(self.scroll_widget)
self.right_layout.addWidget(self.scroll_area)
self.right_frame.setLayout(self.right_layout)
layout.addWidget(self.right_frame, stretch=78)
self.setLayout(layout)
font_path = "fonts/SDK_SC_Web65.ttf"
if os.path.exists(font_path):
font_id = QFontDatabase.addApplicationFont(font_path)
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
QApplication.setFont(QFont(font_family))
else:
logging.warning("Font file not found, using default font.")
self.load_player_list()
def load_player_list(self):
for i in reversed(range(self.player_buttons_frame.count())):
widget = self.player_buttons_frame.itemAt(i).widget()
if widget is not None:
widget.deleteLater()
if os.path.exists(SAVE_DIR):
for uid in os.listdir(SAVE_DIR):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.isdir(player_dir):
with open(os.path.join(player_dir, "player_data.json"), 'r', encoding='utf-8') as f:
data = json.load(f)
player_name = data['player']['nickname']
player_level = data['player']['level']
player_widget = QFrame()
player_layout = QHBoxLayout(player_widget)
player_button = QPushButton(f"{player_name} Lv.{player_level}")
player_button.setFixedWidth(350)
player_button.setFixedHeight(80)
player_button.setStyleSheet("""
QPushButton {
border: 1px solid black;
border-radius: 10px;
padding: 8px;
background-color: white;
font-weight: bold;
}
QPushButton:hover {
background-color: lightgray;
}
""")
view_icon = QIcon("image/gui/open.png")
player_button.setIcon(view_icon)
player_button.setIconSize(QSize(40, 40))
player_button.clicked.connect(lambda _, uid=uid: self.load_player_data(uid))
refresh_button = QPushButton()
refresh_button.setIcon(QIcon("image/gui/update.png"))
refresh_button.setIconSize(QSize(40, 40))
refresh_button.setFixedSize(60, 60)
refresh_button.setContentsMargins(5, 0, 5, 0)
refresh_button.clicked.connect(lambda _, uid=uid: self.refresh_player_data(uid))
refresh_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
padding: 0px;
}
QPushButton:hover {
background-color: rgba(0, 0, 255, 0.3);
}
""")
delete_button = QPushButton()
delete_button.setIcon(QIcon("image/gui/delete.png"))
delete_button.setIconSize(QSize(40, 40))
delete_button.setFixedSize(60, 60)
delete_button.setContentsMargins(5, 0, 5, 0)
delete_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
padding: 0px;
}
QPushButton:hover {
background-color: rgba(255, 0, 0, 0.3);
}
""")
delete_button.clicked.connect(lambda _, uid=uid: self.delete_player_data(uid))
player_layout.addWidget(player_button)
player_layout.addWidget(refresh_button)
player_layout.addWidget(delete_button)
self.player_buttons_frame.addWidget(player_widget)
def load_player_data(self, uid):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.exists(player_dir):
self.current_data = []
for file_name in os.listdir(player_dir):
if file_name.endswith('.pkl'):
with open(os.path.join(player_dir, file_name), 'rb') as f:
character_data = pickle.load(f)
self.current_data.append(character_data)
with open(os.path.join(player_dir, "player_data.json"), 'r', encoding='utf-8') as f:
self.current_player = json.load(f)['player']
self.display_player_data(self.current_data)
logging.info(f"Loaded character data from .pkl files for UID {uid}")
def refresh_player_data(self, uid):
self.fetch_data(uid)
self.load_player_data(uid)
def clear_right_layout(self):
while self.scroll_layout.count():
item = self.scroll_layout.takeAt(0)
widget = item.widget()
if widget:
widget.deleteLater()
else:
sub_layout = item.layout()
if sub_layout:
while sub_layout.count():
sub_item = sub_layout.takeAt(0)
sub_widget = sub_item.widget()
if sub_widget:
sub_widget.deleteLater()
sub_layout.deleteLater()
def delete_player_data(self, uid):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.exists(player_dir):
import shutil
shutil.rmtree(player_dir)
self.load_player_list()
logging.info(f"Deleted player data for UID {uid}")
def prompt_for_uid(self):
uid, ok = QInputDialog.getText(self, "输入 UID", "请输入玩家 UID:")
if ok and uid:
self.fetch_data(uid.strip())
def fetch_data(self, uid):
if len(uid) != 9 or not uid.isdigit() or uid.startswith('0'):
QMessageBox.critical(self, "Invalid UID", "<b>UID必须是9位数字且不能以 '0' 开头。请重试。</b>")
logging.warning("Attempted to fetch data with invalid UID")
return
url = f"https://api.mihomo.me/sr_info_parsed/{uid}?lang=cn"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
self.save_data(uid, data)
self.load_player_list()
logging.info(f"Fetched data for UID {uid}")
except requests.RequestException as e:
QMessageBox.critical(self, "Fetch Failed", "<b>无法获取数据,请检查UID或网络连接。</b>")
logging.error(f"Error fetching data: {e}")
def save_data(self, uid, data):
player_dir = os.path.join(SAVE_DIR, uid)
os.makedirs(player_dir, exist_ok=True)
for character in data['characters']:
char_file_path = os.path.join(player_dir, f"{character['id']}.pkl")
with open(char_file_path, 'wb') as f:
pickle.dump(character, f)
logging.info(f"Character data saved for {character['name']} (ID: {character['id']})")
with open(os.path.join(player_dir, "player_data.json"), 'w', encoding='utf-8') as f:
json.dump(data, f)
logging.info(f"Data saved for UID {uid}")
def display_player_data(self, characters):
self.clear_right_layout()
if self.current_player:
player_info = QLabel(f"<b style='font-size:48px;'>{self.current_player['nickname']}</b><br>"
f"<b style='font-size:26px; font-weight:bold;'>UID:</b> "
f"<b style='font-size:35px; font-weight:bold;'>{self.current_player['uid']}</b><br><br>")
self.scroll_layout.addWidget(player_info)
grid_layout = QGridLayout()
spacing = 20
grid_layout.setSpacing(spacing)
button_width = 280
image_width = 280
image_height = 384
available_width = self.right_frame.width() - (spacing * 2)
buttons_per_row = max(1, available_width // (button_width + spacing))
for index, character in enumerate(characters):
char_button = QPushButton()
char_pixmap = QPixmap(f"image/avataricon/{character['id']}.png").scaled(image_width, image_height, Qt.KeepAspectRatio)
char_button.setIcon(QIcon(char_pixmap))
char_button.setIconSize(QSize(image_width, image_height))
char_button.setFixedSize(image_width, image_height)
element = character['element']['name']
border_color = self.element_colors.get(element, '#000000')
logging.debug(f"Element: {element}, Border Color: {border_color}")
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(15)
shadow.setColor(QColor(border_color))
shadow.setOffset(0, 0)
char_button.setGraphicsEffect(shadow)
char_button.setStyleSheet(f"""
QPushButton {{
border: 5px solid {border_color};
border-radius: 15px;
background-color: transparent;
}}
QPushButton:hover {{
background-color: rgba(0, 0, 0, 0.1);
}}
""")
char_button.clicked.connect(lambda _, char=character: self.show_character_details(char))
row = index // buttons_per_row
column = index % buttons_per_row
grid_layout.addWidget(char_button, row, column)
self.scroll_layout.addLayout(grid_layout)
def show_character_details(self, character):
# 每次显示角色详情时创建新的窗口实例
detail_window = CharacterDetailWindow(character, self.element_colors, self.paths_mapping)
self.detail_windows.append(detail_window) # 将新窗口实例添加到列表
detail_window.show()
def open_cmd(self):
os.system("start cmd")
logging.info("Opened CMD")
def open_ticket_simulator(self):
reply = QMessageBox.question(self, "Visit Ticket Simulator",
"Would you like to open the wish simulator?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
webbrowser.open("https://hsr.wishsimulator.app/")
logging.info("Opened ticket simulator")
def run_rate_calculator(self):
# 获取用户输入
role_count, ok_pressed = QInputDialog.getInt(self, "角色需求", "请输入所需的限定角色数量:", 1, 1, 100, 1)
if not ok_pressed:
return
weapon_count, ok_pressed = QInputDialog.getInt(self, "武器需求", "请输入所需的限定武器数量:", 1, 1, 100, 1)
if not ok_pressed:
return
# 运行 ratecalc.exe
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-average", str(role_count), str(weapon_count)],
capture_output=True, text=True)
output = result.stdout
QMessageBox.information(self, "Calculation Result", f"Calculation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
super().resizeEvent(event)
if self.current_data:
self.display_player_data(self.current_data)
if name == "main ":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("image/gui/icon.ico"))
window = HSRToolApp()
window.show()
sys.exit(app.exec_()),要求绑定主页silverticket图片的按钮,按下增加一个新的窗口,可以让玩家输入这些参数,然后程序模拟输出结果,你输出完整的cpp和py代码,且不要更改,不要更改,不要更改我的其他代码
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
// 模拟抽卡函数
bool simulatePull(bool& guaranteed, int& pullCount, int poolType) {
double baseRate = 0.006;
int pityStart = (poolType == 1) ? 73 : 63;
int hardPity = (poolType == 1) ? 90 : 80;
double rateIncrease = 0.062;
double pullRate = baseRate;
if (pullCount >= pityStart) {
pullRate += (pullCount - pityStart) * rateIncrease;
}
bool gotGold = (pullCount >= hardPity - 1) || (static_cast<double>(std::rand()) / RAND_MAX) < pullRate;
if (gotGold) {
pullCount = 0; // 出金后重置抽数
if (guaranteed ||
(static_cast<double>(std::rand()) / RAND_MAX) < ((poolType == 1) ? 0.5 : 0.75)) {
guaranteed = false;
return true; // 限定物品
} else {
guaranteed = true;
return false; // 非限定物品
}
} else {
pullCount += 1;
}
return false;
}
// 计算平均抽数
double calculateAveragePulls(int roleCount, int weaponCount) {
int totalPulls = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = false, guaranteedWeapon = false;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = 0, weaponPullCount = 0;
while (roleObtained < roleCount || weaponObtained < weaponCount) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2)) {
weaponObtained++;
}
pulls++;
}
}
totalPulls += pulls;
}
return static_cast<double>(totalPulls) / 10000.0;
}
// 模拟道具数量下的成功率
double simulateWithItems(int roleCount, int weaponCount, int items, int initialRolePulls, int initialWeaponPulls, bool majorPity) {
int successfulSimulations = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = majorPity, guaranteedWeapon = majorPity;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = initialRolePulls, weaponPullCount = initialWeaponPulls;
while (pulls < items) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount && pulls < items) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2)) {
weaponObtained++;
}
pulls++;
}
if (roleObtained >= roleCount && weaponObtained >= weaponCount) {
successfulSimulations++;
break;
}
}
}
return static_cast<double>(successfulSimulations) / 10000.0;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <function> <parameters>..." << std::endl;
return 1;
}
std::srand(std::time(0)); // 设置随机种子
std::string function = argv[1];
if (function == "-average") {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " -average <roleCount> <weaponCount>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
double averagePulls = calculateAveragePulls(roleCount, weaponCount);
std::cout << averagePulls << std::endl;
} else if (function == "-simulate") {
if (argc < 8) {
std::cerr << "Usage: " << argv[0] << " -simulate <roleCount> <weaponCount> <items> <initialRolePulls> <initialWeaponPulls> <majorPity>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int items = std::stoi(argv[4]);
int initialRolePulls = std::stoi(argv[5]);
int initialWeaponPulls = std::stoi(argv[6]);
bool majorPity = std::stoi(argv[7]);
double successRate = simulateWithItems(roleCount, weaponCount, items, initialRolePulls, initialWeaponPulls, majorPity);
std::cout << successRate * 100.0 << "%" << std::endl;
} else {
std::cerr << "Invalid function specified." << std::endl;
return 1;
}
return 0;
}
Python程序 为满足通过按钮交互进行模拟,请在 run_rate_calculator 方法中增加对新按钮功能的响应:
python Copy code
def open_silver_ticket_simulator(self):
# 获取用户输入
role_count, ok_pressed = QInputDialog.getInt(self, "角色需求", "请输入所需的限定角色数量:", 1, 1, 100, 1)
if not ok_pressed:
return
weapon_count, ok_pressed = QInputDialog.getInt(self, "武器需求", "请输入所需的限定武器数量:", 1, 1, 100, 1)
if not ok_pressed:
return
items, ok_pressed = QInputDialog.getInt(self, "拥有的道具", "请输入拥有的道具数量:", 1, 0, 10000, 1)
if not ok_pressed:
return
initial_role_pulls, ok_pressed = QInputDialog.getInt(self, "初始角色抽数", "请输入角色池的初始抽数:", 0, 0, 89, 1)
if not ok_pressed:
return
initial_weapon_pulls, ok_pressed = QInputDialog.getInt(self, "初始武器抽数", "请输入武器池的初始抽数:", 0, 0, 79, 1)
if not ok_pressed:
return
major_pity, ok_pressed = QInputDialog.getItem(self, "大保底", "是否大保底:", ["否", "是"], 0, False)
if not ok_pressed:
return
major_pity_bool = True if major_pity == "是" else False
# 运行 ratecalc.exe
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-simulate", str(role_count), str(weapon_count), str(items),
str(initial_role_pulls), str(initial_weapon_pulls), str(int(major_pity_bool))],
capture_output=True, text=True)
output = result.stdout
QMessageBox.information(self, "Simulation Result", f"Simulation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
确保为silver_ticket_button添加正确的信号槽链接:
python Copy code
self.silver_ticket_button.clicked.connect(self.open_silver_ticket_simulator)
以上是对你的C++代码的改进以及Python代码的部分实现。通过这些修改,你可以在Python界面中实现对C++程序的调用,并根据用户的输入进行模拟,反馈结果显示在界面上。确保将C++程序编译为可执行的ratecalc.exe,并正确放置在程序可访问的目录中。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
// 独立模拟角色池或武器池的抽卡
bool simulatePull(bool& guaranteed, int& pullCount, int poolType, bool majorPity) {
const double baseRate = 0.006;
const int pityStart = (poolType == 1) ? 73 : 63;
const int hardPity = (poolType == 1) ? 90 : 80;
const double rateIncrease = 0.062;
double pullRate = baseRate;
if (pullCount >= pityStart) {
pullRate += (pullCount - pityStart) * rateIncrease;
}
bool gotGold = (pullCount >= hardPity - 1) || (static_cast<double>(std::rand()) / RAND_MAX) < pullRate;
if (gotGold) {
pullCount = 0; // 出金重置抽数
if (guaranteed ||
(static_cast<double>(std::rand()) / RAND_MAX) < ((poolType == 1) ? 0.5 : 0.75)) {
guaranteed = false;
return true; // 获取限定物品
} else {
guaranteed = true;
return false; // 非限定
}
} else {
pullCount += 1;
}
return false;
}
double calculateAveragePulls(int roleCount, int weaponCount) {
int totalPulls = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = false, guaranteedWeapon = false;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = 0, weaponPullCount = 0;
while (roleObtained < roleCount || weaponObtained < weaponCount) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, false)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, false)) {
weaponObtained++;
}
pulls++;
}
}
totalPulls += pulls;
}
return static_cast<double>(totalPulls) / 10000.0;
}
double simulateWithItems(int roleCount, int weaponCount, int items, int initialRolePulls, int initialWeaponPulls, bool majorPityRole, bool majorPityWeapon) {
int successfulSimulations = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = majorPityRole, guaranteedWeapon = majorPityWeapon;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = initialRolePulls, weaponPullCount = initialWeaponPulls;
while (pulls < items) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, majorPityRole)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount && pulls < items) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, majorPityWeapon)) {
weaponObtained++;
}
pulls++;
}
if (roleObtained >= roleCount && weaponObtained >= weaponCount) {
successfulSimulations++;
break;
}
}
}
return static_cast<double>(successfulSimulations) / 10000.0;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <function> <parameters>..." << std::endl;
return 1;
}
std::srand(std::time(0)); // 设置随机种子
std::string function = argv[1];
if (function == "-average") {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " -average <roleCount> <weaponCount>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
double averagePulls = calculateAveragePulls(roleCount, weaponCount);
std::cout << averagePulls << std::endl;
} else if (function == "-simulate") {
if (argc < 9) {
std::cerr << "Usage: " << argv[0] << " -simulate <roleCount> <weaponCount> <items> <initialRolePulls> <initialWeaponPulls> <majorPityRole> <majorPityWeapon>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int items = std::stoi(argv[4]);
int initialRolePulls = std::stoi(argv[5]);
int initialWeaponPulls = std::stoi(argv[6]);
bool majorPityRole = std::stoi(argv[7]);
bool majorPityWeapon = std::stoi(argv[8]);
double successRate = simulateWithItems(roleCount, weaponCount, items, initialRolePulls, initialWeaponPulls, majorPityRole, majorPityWeapon);
std::cout << successRate * 100.0 << "%" << std::endl;
} else {
std::cerr << "Invalid function specified." << std::endl;
return 1;
}
return 0;
}
更新的Python程序 现在,扩展Python程序以添加新功能,分别处理角色池和武器池的大保底:
python Copy code
def open_silver_ticket_simulator(self):
# 让用户输入多个参数
role_count, ok_pressed = QInputDialog.getInt(self, "角色需求", "请输入所需的限定角色数量:", 1, 1, 100, 1)
if not ok_pressed:
return
weapon_count, ok_pressed = QInputDialog.getInt(self, "武器需求", "请输入所需的限定武器数量:", 1, 1, 100, 1)
if not ok_pressed:
return
items, ok_pressed = QInputDialog.getInt(self, "拥有的道具", "请输入拥有的道具数量:", 1, 0, 10000, 1)
if not ok_pressed:
return
initial_role_pulls, ok_pressed = QInputDialog.getInt(self, "初始角色抽数", "请输入角色池的初始抽数:", 0, 0, 89, 1)
if not ok_pressed:
return
initial_weapon_pulls, ok_pressed = QInputDialog.getInt(self, "初始武器抽数", "请输入武器池的初始抽数:", 0, 0, 79, 1)
if not ok_pressed:
return
major_pity_role, ok_pressed = QInputDialog.getItem(self, "角色大保底", "角色池是否大保底:", ["否", "是"], 0, False)
if not ok_pressed:
return
major_pity_weapon = QInputDialog.getItem(self, "武器大保底", "武器池是否大保底:", ["否", "是"], 0, False)
if not ok_pressed:
return
major_pity_role_bool = True if major_pity_role == "是" else False
major_pity_weapon_bool = True if major_pity_weapon == "是" else False
# 运行 ratecalc.exe
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-simulate",
str(role_count), str(weapon_count), str(items),
str(initial_role_pulls), str(initial_weapon_pulls),
str(int(major_pity_role_bool)), str(int(major_pity_weapon_bool))],
capture_output=True, text=True)
output = result.stdout.strip()
QMessageBox.information(self, "Simulation Result", f"Simulation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
以上代码适应于用户单独设定每个池的保底状态以及初始化池的抽数状态,并能对不同池进行独立模拟。请确保 ratecalc.exe 在指定路径存在,并且设置了正确的执行权限,使其能够被 Python 调用。这样,用户可以通过应用程序界面输入参数,并获取模拟结果。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
// 独立模拟角色池或武器池的抽卡
bool simulatePull(bool& guaranteed, int& pullCount, int poolType, bool majorPity) {
const double baseRate = 0.006;
const int pityStart = (poolType == 1) ? 73 : 63;
const int hardPity = (poolType == 1) ? 90 : 80;
const double rateIncrease = 0.062;
double pullRate = baseRate;
if (pullCount >= pityStart) {
pullRate += (pullCount - pityStart) * rateIncrease;
}
bool gotGold = (pullCount >= hardPity - 1) || (static_cast<double>(std::rand()) / RAND_MAX) < pullRate;
if (gotGold) {
pullCount = 0; // 出金重置抽数
if (guaranteed || (majorPity) ||
(static_cast<double>(std::rand()) / RAND_MAX) < ((poolType == 1) ? 0.5 : 0.75)) {
guaranteed = false;
return true; // 获取限定物品
} else {
guaranteed = true;
return false; // 非限定
}
} else {
pullCount += 1;
}
return false;
}
double calculateAveragePulls(int roleCount, int weaponCount) {
int totalPulls = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = false, guaranteedWeapon = false;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = 0, weaponPullCount = 0;
while (roleObtained < roleCount || weaponObtained < weaponCount) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, false)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, false)) {
weaponObtained++;
}
pulls++;
}
}
totalPulls += pulls;
}
return static_cast<double>(totalPulls) / 10000.0;
}
double simulateWithItems(int roleCount, int weaponCount, int items, int initialRolePulls, int initialWeaponPulls, bool majorPityRole, bool majorPityWeapon) {
int successfulSimulations = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = majorPityRole, guaranteedWeapon = majorPityWeapon;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = initialRolePulls, weaponPullCount = initialWeaponPulls;
while (pulls < items) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, majorPityRole)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount && pulls < items) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, majorPityWeapon)) {
weaponObtained++;
}
pulls++;
}
if (roleObtained >= roleCount && weaponObtained >= weaponCount) {
successfulSimulations++;
break;
}
}
}
return static_cast<double>(successfulSimulations) / 10000.0;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <function> <parameters>..." << std::endl;
return 1;
}
std::srand(std::time(0)); // 设置随机种子
std::string function = argv[1];
if (function == "-average") {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " -average <roleCount> <weaponCount>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
double averagePulls = calculateAveragePulls(roleCount, weaponCount);
std::cout << averagePulls << std::endl;
} else if (function == "-simulate") {
if (argc < 9) {
std::cerr << "Usage: " << argv[0] << " -simulate <roleCount> <weaponCount> <items> <initialRolePulls> <initialWeaponPulls> <majorPityRole> <majorPityWeapon>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int items = std::stoi(argv[4]);
int initialRolePulls = std::stoi(argv[5]);
int initialWeaponPulls = std::stoi(argv[6]);
bool majorPityRole = std::stoi(argv[7]);
bool majorPityWeapon = std::stoi(argv[8]);
double successRate = simulateWithItems(roleCount, weaponCount, items, initialRolePulls, initialWeaponPulls, majorPityRole, majorPityWeapon);
std::cout << successRate * 100.0 << "%" << std::endl;
} else {
std::cerr << "Invalid function specified." << std::endl;
return 1;
}
return 0;
}
更新的Python程序 在Python程序中,仅需将新的功能绑定到按钮上,并维持其他功能不变。
python Copy code
# 添加以下方法到现有的HSRToolApp类中,不要更改其他代码块
def open_silver_ticket_simulator(self):
# 允许用户输入参数
role_count, ok_pressed = QInputDialog.getInt(self, "角色需求", "请输入所需的限定角色数量:", 1, 1, 100, 1)
if not ok_pressed:
return
weapon_count, ok_pressed = QInputDialog.getInt(self, "武器需求", "请输入所需的限定武器数量:", 1, 1, 100, 1)
if not ok_pressed:
return
items, ok_pressed = QInputDialog.getInt(self, "拥有的道具", "请输入拥有的道具数量:", 1, 0, 10000, 1)
if not ok_pressed:
return
initial_role_pulls, ok_pressed = QInputDialog.getInt(self, "初始角色抽数", "请输入角色池的初始抽数:", 0, 0, 89, 1)
if not ok_pressed:
return
initial_weapon_pulls, ok_pressed = QInputDialog.getInt(self, "初始武器抽数", "请输入武器池的初始抽数:", 0, 0, 79, 1)
if not ok_pressed:
return
major_pity_role, ok_pressed = QInputDialog.getItem(self, "角色大保底", "角色池是否大保底:", ["否", "是"], 0, False)
if not ok_pressed:
return
major_pity_weapon, ok_pressed = QInputDialog.getItem(self, "武器大保底", "武器池是否大保底:", ["否", "是"], 0, False)
if not ok_pressed:
return
major_pity_role_bool = True if major_pity_role == "是" else False
major_pity_weapon_bool = True if major_pity_weapon == "是" else False
# 运行ratecalc.exe
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-simulate",
str(role_count), str(weapon_count), str(items),
str(initial_role_pulls), str(initial_weapon_pulls),
str(int(major_pity_role_bool)), str(int(major_pity_weapon_bool))],
capture_output=True, text=True)
output = result.stdout.strip()
QMessageBox.information(self, "Simulation Result", f"Simulation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
# 确保将silver_ticket_button的点击事件连接到open_silver_ticket_simulator方法上
self.silver_ticket_button.clicked.connect(self.open_silver_ticket_simulator)
请确保将C++程序编译为可执行文件并正确路径设置在expansions目录下,并在Python程序中用适当的位置调用可执行文件。其余的已有代码和逻辑会保持不变。
import sys
import os
import json
import logging
import requests
import pickle
from datetime import datetime
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QMessageBox, QScrollArea, QFrame, QInputDialog,
QGridLayout, QGraphicsDropShadowEffect, QDesktopWidget)
from PyQt5.QtGui import QFont, QIcon, QPixmap, QFontDatabase, QColor, QBrush, QPalette
from PyQt5.QtCore import Qt, QSize
import subprocess
import webbrowser
# 定义日志路径和配置信息
SAVE_DIR = "./saves/players"
CONFIG_DIR = "./config/software/"
ELEMENT_COLOR_FILE = os.path.join(CONFIG_DIR, "elementcolor.json")
PATHS_MAPPING_FILE = os.path.join(CONFIG_DIR, "pathsmapping.json")
# 设置日志记录
log_dir = "./logs/"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_filename = f"srtool_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(os.path.join(log_dir, log_filename), encoding='utf-8')
])
# 加载元素颜色配置
def load_element_colors():
if not os.path.exists(ELEMENT_COLOR_FILE):
logging.error(f"Element color configuration file not found: {ELEMENT_COLOR_FILE}")
return {}
with open(ELEMENT_COLOR_FILE, 'r', encoding='utf-8') as f:
element_colors = json.load(f)
logging.debug(f"Loaded element colors: {element_colors}")
return element_colors
# 加载命途映射配置
def load_paths_mapping():
if not os.path.exists(PATHS_MAPPING_FILE):
logging.error(f"Paths mapping configuration file not found: {PATHS_MAPPING_FILE}")
return {}
with open(PATHS_MAPPING_FILE, 'r', encoding='utf-8') as f:
paths_mapping = json.load(f)
logging.debug(f"Loaded paths mapping: {paths_mapping}")
return paths_mapping
# 角色详细信息窗口类
class CharacterDetailWindow(QWidget):
def __init__(self, character, element_colors, paths_mapping):
super().__init__()
self.character = character
self.element_colors = element_colors
self.paths_mapping = paths_mapping
self.initUI()
def initUI(self):
self.setWindowTitle(f"{self.character['name']} - Detailed Information")
self.showMaximized()
# 设置窗口的背景图片
self.set_background()
# 创建主布局
main_layout = QVBoxLayout(self)
main_layout.setContentsMargins(0, 0, 0, 0)
# 创建一个QScrollArea
scroll_area = QScrollArea(self)
scroll_area.setWidgetResizable(True)
scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
# 创建一个容器小部件,并将其放置在scroll area中
container = QWidget()
scroll_area.setWidget(container)
# 在容器小部件上设置布局
layout = QVBoxLayout(container)
layout.setContentsMargins(50, 50, 50, 50)
# 添加角色立绘
splashart_path = f"image/splashart/{self.character['id']}.png"
splashart_pixmap = QPixmap(splashart_path).scaled(768, 768, Qt.KeepAspectRatio, Qt.SmoothTransformation)
splashart_label = QLabel(self)
splashart_label.setPixmap(splashart_pixmap)
# 添加命途符号
path_name = self.character['path']['name'].lower()
path_icon_key = self.paths_mapping.get(path_name, None)
if path_icon_key:
path_icon_path = f"image/path/{path_icon_key}.png"
path_pixmap = QPixmap(path_icon_path).scaled(128, 128, Qt.KeepAspectRatio, Qt.SmoothTransformation)
path_icon_label = QLabel(splashart_label)
path_icon_label.setPixmap(path_pixmap)
path_icon_label.move(10, 10)
layout.addWidget(splashart_label, alignment=Qt.AlignLeft | Qt.AlignTop)
# 将scroll_area加入主布局
main_layout.addWidget(scroll_area)
def set_background(self):
# 设置固定背景图片
palette = self.palette()
background_pixmap = QPixmap("image/gui/background.jpeg").scaled(self.size(), Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)
palette.setBrush(QPalette.Window, QBrush(background_pixmap))
self.setPalette(palette)
def resizeEvent(self, event):
# 调整背景图片大小以覆盖整个窗口
self.set_background()
super().resizeEvent(event)
# 主应用程序类
class HSRToolApp(QWidget):
def __init__(self):
super().__init__()
self.current_data = None
self.current_player = None
self.element_colors = load_element_colors()
self.paths_mapping = load_paths_mapping()
self.detail_windows = [] # 存储角色详细信息窗口的列表
self.initUI()
def initUI(self):
self.setWindowTitle("HSR Toolkit")
self.setWindowIcon(QIcon("image/gui/icon.ico"))
self.setGeometry(0, 0, 800, 600)
self.showMaximized()
layout = QHBoxLayout(self)
self.left_frame = QFrame()
self.left_layout = QVBoxLayout()
self.left_layout.setAlignment(Qt.AlignTop)
self.add_player_button = QPushButton("添加玩家数据")
self.add_player_button.setIcon(QIcon("image/gui/add.svg"))
self.add_player_button.setIconSize(QSize(24, 24))
self.add_player_button.setFixedWidth(600)
self.add_player_button.setStyleSheet("""
QPushButton {
border: 2px solid black;
border-radius: 10px;
color: gray;
background-color: white;
padding: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: lightblue;
color: black;
}
""")
self.add_player_button.setToolTip("点击添加玩家数据")
self.add_player_button.clicked.connect(self.prompt_for_uid)
self.left_layout.addWidget(self.add_player_button, alignment=Qt.AlignTop)
self.player_buttons_frame = QVBoxLayout()
self.player_buttons_frame.setAlignment(Qt.AlignTop)
self.left_layout.addLayout(self.player_buttons_frame)
self.cmd_button = QPushButton()
self.gold_ticket_button = QPushButton()
self.silver_ticket_button = QPushButton()
cmd_pixmap = QPixmap("image/gui/cmd.png").scaled(80, 80, Qt.KeepAspectRatio)
gold_ticket_pixmap = QPixmap("image/gui/GoldTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
silver_ticket_pixmap = QPixmap("image/gui/SilverTicket.png").scaled(80, 80, Qt.KeepAspectRatio)
self.cmd_button.setIcon(QIcon(cmd_pixmap))
self.cmd_button.setIconSize(cmd_pixmap.size())
self.cmd_button.setFixedSize(80, 80)
self.gold_ticket_button.setIcon(QIcon(gold_ticket_pixmap))
self.gold_ticket_button.setIconSize(gold_ticket_pixmap.size())
self.gold_ticket_button.setFixedSize(80, 80)
self.silver_ticket_button.setIcon(QIcon(silver_ticket_pixmap))
self.silver_ticket_button.setIconSize(silver_ticket_pixmap.size())
self.silver_ticket_button.setFixedSize(80, 80)
self.cmd_button.clicked.connect(self.open_cmd)
self.gold_ticket_button.clicked.connect(self.open_ticket_simulator)
self.silver_ticket_button.clicked.connect(self.open_silver_ticket_simulator)
bottom_layout = QHBoxLayout()
bottom_layout.addWidget(self.cmd_button)
bottom_layout.addWidget(self.gold_ticket_button)
bottom_layout.addWidget(self.silver_ticket_button)
self.left_layout.addStretch()
self.left_layout.addLayout(bottom_layout)
self.left_frame.setLayout(self.left_layout)
layout.addWidget(self.left_frame, stretch=22)
self.right_frame = QFrame()
self.right_layout = QVBoxLayout()
self.right_layout.setAlignment(Qt.AlignTop)
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_widget = QWidget()
self.scroll_layout = QVBoxLayout()
self.scroll_layout.setAlignment(Qt.AlignTop)
self.scroll_widget.setLayout(self.scroll_layout)
self.scroll_area.setWidget(self.scroll_widget)
self.right_layout.addWidget(self.scroll_area)
self.right_frame.setLayout(self.right_layout)
layout.addWidget(self.right_frame, stretch=78)
self.setLayout(layout)
font_path = "fonts/SDK_SC_Web65.ttf"
if os.path.exists(font_path):
font_id = QFontDatabase.addApplicationFont(font_path)
font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
QApplication.setFont(QFont(font_family))
else:
logging.warning("Font file not found, using default font.")
self.load_player_list()
def load_player_list(self):
for i in reversed(range(self.player_buttons_frame.count())):
widget = self.player_buttons_frame.itemAt(i).widget()
if widget is not None:
widget.deleteLater()
if os.path.exists(SAVE_DIR):
for uid in os.listdir(SAVE_DIR):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.isdir(player_dir):
with open(os.path.join(player_dir, "player_data.json"), 'r', encoding='utf-8') as f:
data = json.load(f)
player_name = data['player']['nickname']
player_level = data['player']['level']
player_widget = QFrame()
player_layout = QHBoxLayout(player_widget)
player_button = QPushButton(f"{player_name} Lv.{player_level}")
player_button.setFixedWidth(350)
player_button.setFixedHeight(80)
player_button.setStyleSheet("""
QPushButton {
border: 1px solid black;
border-radius: 10px;
padding: 8px;
background-color: white;
font-weight: bold;
}
QPushButton:hover {
background-color: lightgray;
}
""")
view_icon = QIcon("image/gui/open.png")
player_button.setIcon(view_icon)
player_button.setIconSize(QSize(40, 40))
player_button.clicked.connect(lambda _, uid=uid: self.load_player_data(uid))
refresh_button = QPushButton()
refresh_button.setIcon(QIcon("image/gui/update.png"))
refresh_button.setIconSize(QSize(40, 40))
refresh_button.setFixedSize(60, 60)
refresh_button.setContentsMargins(5, 0, 5, 0)
refresh_button.clicked.connect(lambda _, uid=uid: self.refresh_player_data(uid))
refresh_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
padding: 0px;
}
QPushButton:hover {
background-color: rgba(0, 0, 255, 0.3);
}
""")
delete_button = QPushButton()
delete_button.setIcon(QIcon("image/gui/delete.png"))
delete_button.setIconSize(QSize(40, 40))
delete_button.setFixedSize(60, 60)
delete_button.setContentsMargins(5, 0, 5, 0)
delete_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
padding: 0px;
}
QPushButton:hover {
background-color: rgba(255, 0, 0, 0.3);
}
""")
delete_button.clicked.connect(lambda _, uid=uid: self.delete_player_data(uid))
player_layout.addWidget(player_button)
player_layout.addWidget(refresh_button)
player_layout.addWidget(delete_button)
self.player_buttons_frame.addWidget(player_widget)
def load_player_data(self, uid):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.exists(player_dir):
self.current_data = []
for file_name in os.listdir(player_dir):
if file_name.endswith('.pkl'):
with open(os.path.join(player_dir, file_name), 'rb') as f:
character_data = pickle.load(f)
self.current_data.append(character_data)
with open(os.path.join(player_dir, "player_data.json"), 'r', encoding='utf-8') as f:
self.current_player = json.load(f)['player']
self.display_player_data(self.current_data)
logging.info(f"Loaded character data from .pkl files for UID {uid}")
def refresh_player_data(self, uid):
self.fetch_data(uid)
self.load_player_data(uid)
def clear_right_layout(self):
while self.scroll_layout.count():
item = self.scroll_layout.takeAt(0)
widget = item.widget()
if widget:
widget.deleteLater()
else:
sub_layout = item.layout()
if sub_layout:
while sub_layout.count():
sub_item = sub_layout.takeAt(0)
sub_widget = sub_item.widget()
if sub_widget:
sub_widget.deleteLater()
sub_layout.deleteLater()
def delete_player_data(self, uid):
player_dir = os.path.join(SAVE_DIR, uid)
if os.path.exists(player_dir):
import shutil
shutil.rmtree(player_dir)
self.load_player_list()
logging.info(f"Deleted player data for UID {uid}")
def prompt_for_uid(self):
uid, ok = QInputDialog.getText(self, "输入 UID", "请输入玩家 UID:")
if ok and uid:
self.fetch_data(uid.strip())
def fetch_data(self, uid):
if len(uid) != 9 or not uid.isdigit() or uid.startswith('0'):
QMessageBox.critical(self, "Invalid UID", "<b>UID必须是9位数字且不能以 '0' 开头。请重试。</b>")
logging.warning("Attempted to fetch data with invalid UID")
return
url = f"https://api.mihomo.me/sr_info_parsed/{uid}?lang=cn"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
self.save_data(uid, data)
self.load_player_list()
logging.info(f"Fetched data for UID {uid}")
except requests.RequestException as e:
QMessageBox.critical(self, "Fetch Failed", "<b>无法获取数据,请检查UID或网络连接。</b>")
logging.error(f"Error fetching data: {e}")
def save_data(self, uid, data):
player_dir = os.path.join(SAVE_DIR, uid)
os.makedirs(player_dir, exist_ok=True)
for character in data['characters']:
char_file_path = os.path.join(player_dir, f"{character['id']}.pkl")
with open(char_file_path, 'wb') as f:
pickle.dump(character, f)
logging.info(f"Character data saved for {character['name']} (ID: {character['id']})")
with open(os.path.join(player_dir, "player_data.json"), 'w', encoding='utf-8') as f:
json.dump(data, f)
logging.info(f"Data saved for UID {uid}")
def display_player_data(self, characters):
self.clear_right_layout()
if self.current_player:
player_info = QLabel(f"<b style='font-size:48px;'>{self.current_player['nickname']}</b><br>"
f"<b style='font-size:26px; font-weight:bold;'>UID:</b> "
f"<b style='font-size:35px; font-weight:bold;'>{self.current_player['uid']}</b><br><br>")
self.scroll_layout.addWidget(player_info)
grid_layout = QGridLayout()
spacing = 20
grid_layout.setSpacing(spacing)
button_width = 280
image_width = 280
image_height = 384
available_width = self.right_frame.width() - (spacing * 2)
buttons_per_row = max(1, available_width // (button_width + spacing))
for index, character in enumerate(characters):
char_button = QPushButton()
char_pixmap = QPixmap(f"image/avataricon/{character['id']}.png").scaled(image_width, image_height, Qt.KeepAspectRatio)
char_button.setIcon(QIcon(char_pixmap))
char_button.setIconSize(QSize(image_width, image_height))
char_button.setFixedSize(image_width, image_height)
element = character['element']['name']
border_color = self.element_colors.get(element, '#000000')
logging.debug(f"Element: {element}, Border Color: {border_color}")
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(15)
shadow.setColor(QColor(border_color))
shadow.setOffset(0, 0)
char_button.setGraphicsEffect(shadow)
char_button.setStyleSheet(f"""
QPushButton {{
border: 5px solid {border_color};
border-radius: 15px;
background-color: transparent;
}}
QPushButton:hover {{
background-color: rgba(0, 0, 0, 0.1);
}}
""")
char_button.clicked.connect(lambda _, char=character: self.show_character_details(char))
row = index // buttons_per_row
column = index % buttons_per_row
grid_layout.addWidget(char_button, row, column)
self.scroll_layout.addLayout(grid_layout)
def show_character_details(self, character):
# 每次显示角色详情时创建新的窗口实例
detail_window = CharacterDetailWindow(character, self.element_colors, self.paths_mapping)
self.detail_windows.append(detail_window) # 将新窗口实例添加到列表
detail_window.show()
def open_cmd(self):
os.system("start cmd")
logging.info("Opened CMD")
def open_ticket_simulator(self):
reply = QMessageBox.question(self, "Visit Ticket Simulator",
"Would you like to open the wish simulator?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
webbrowser.open("https://hsr.wishsimulator.app/")
logging.info("Opened ticket simulator")
def run_rate_calculator(self):
# 获取用户输入
role_count, ok_pressed = QInputDialog.getInt(self, "角色需求", "请输入所需的限定角色数量:", 1, 1, 100, 1)
if not ok_pressed:
return
weapon_count, ok_pressed = QInputDialog.getInt(self, "武器需求", "请输入所需的限定武器数量:", 1, 1, 100, 1)
if not ok_pressed:
return
# 运行 ratecalc.exe
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-average", str(role_count), str(weapon_count)],
capture_output=True, text=True)
output = result.stdout
QMessageBox.information(self, "Calculation Result", f"Calculation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
def open_silver_ticket_simulator(self):
# 允许用户输入参数
role_count, ok_pressed = QInputDialog.getInt(self, "角色需求", "请输入所需的限定角色数量:", 1, 1, 100, 1)
if not ok_pressed:
return
weapon_count, ok_pressed = QInputDialog.getInt(self, "武器需求", "请输入所需的限定武器数量:", 1, 1, 100, 1)
if not ok_pressed:
return
items, ok_pressed = QInputDialog.getInt(self, "拥有的道具", "请输入拥有的道具数量:", 1, 0, 10000, 1)
if not ok_pressed:
return
initial_role_pulls, ok_pressed = QInputDialog.getInt(self, "初始角色抽数", "请输入角色池的初始抽数:", 0, 0, 89, 1)
if not ok_pressed:
return
initial_weapon_pulls, ok_pressed = QInputDialog.getInt(self, "初始武器抽数", "请输入武器池的初始抽数:", 0, 0, 79, 1)
if not ok_pressed:
return
major_pity_role, ok_pressed = QInputDialog.getItem(self, "角色大保底", "角色池是否大保底:", ["否", "是"], 0, False)
if not ok_pressed:
return
major_pity_weapon, ok_pressed = QInputDialog.getItem(self, "武器大保底", "武器池是否大保底:", ["否", "是"], 0, False)
if not ok_pressed:
return
major_pity_role_bool = True if major_pity_role == "是" else False
major_pity_weapon_bool = True if major_pity_weapon == "是" else False
# 运行ratecalc.exe
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-simulate",
str(role_count), str(weapon_count), str(items),
str(initial_role_pulls), str(initial_weapon_pulls),
str(int(major_pity_role_bool)), str(int(major_pity_weapon_bool))],
capture_output=True, text=True)
output = result.stdout.strip()
QMessageBox.information(self, "Simulation Result", f"Simulation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("image/gui/icon.ico"))
window = HSRToolApp()
window.show()
sys.exit(app.exec_())
在这个代码中,我添加了 open_silver_ticket_simulator 方法,并将其绑定到 self.silver_ticket_button。此功能实现了对角色池和武器池的独立模拟,包括用户输入大保底和初始抽数。请确保ratecalc.exe可执行文件在指定路径,并具备执行权限。其他现有代码保持不变。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <string>
// 独立模拟角色池或武器池的抽卡
bool simulatePull(bool& guaranteed, int& pullCount, int poolType, bool majorPity, int& fourStarStreak, int& fourStars) {
const double baseRate = 0.006;
const double baseRateFourStar = 0.10;
const int pityStart = (poolType == 1) ? 73 : 63;
const int hardPity = (poolType == 1) ? 90 : 80;
const double rateIncrease = 0.062;
double pullRate = baseRate;
if (pullCount >= pityStart) {
pullRate += (pullCount - pityStart) * rateIncrease;
}
bool gotGold = (pullCount >= hardPity - 1) || (static_cast<double>(std::rand()) / RAND_MAX) < pullRate;
bool gotFourStar = ((++fourStarStreak % 10 == 0) || (static_cast<double>(std::rand()) / RAND_MAX) < baseRateFourStar);
if (gotGold) {
pullCount = 0; // 出金重置抽数
fourStarStreak = 0; // 出金时也要重置四星连续抽数
if (guaranteed || (majorPity) ||
(static_cast<double>(std::rand()) / RAND_MAX) < ((poolType == 1) ? 0.5 : 0.75)) {
guaranteed = false;
return true; // 获取限定物品
} else {
guaranteed = true;
return false; // 非限定
}
}
if (gotFourStar) {
fourStars++;
fourStarStreak = 0; // 重置四星连续抽数
}
pullCount += 1;
return false;
}
double calculateAveragePulls(int roleCount, int weaponCount, int& fourStarCount) {
int totalPulls = 0;
int totalFourStars = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = false, guaranteedWeapon = false;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = 0, weaponPullCount = 0;
int fourStarStreakRole = 0, fourStarStreakWeapon = 0;
int fourStars = 0;
while (roleObtained < roleCount || weaponObtained < weaponCount) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, false, fourStarStreakRole, fourStars)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, false, fourStarStreakWeapon, fourStars)) {
weaponObtained++;
}
pulls++;
}
}
totalPulls += pulls;
totalFourStars += fourStars;
}
fourStarCount = totalFourStars;
return static_cast<double>(totalPulls) / 10000.0;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <function> <parameters>..." << std::endl;
return 1;
}
std::srand(std::time(0)); // 设置随机种子
std::string function = argv[1];
if (function == "-average") {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " -average <roleCount> <weaponCount>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int fourStarCount = 0;
double averagePulls = calculateAveragePulls(roleCount, weaponCount, fourStarCount);
int starJades = static_cast<int>(std::ceil(averagePulls)) * 160;
std::cout << averagePulls << " " << fourStarCount / 10000.0 << " " << starJades << std::endl;
} else {
std::cerr << "Invalid function specified." << std::endl;
return 1;
}
return 0;
}
完整的Python代码 以下是Python代码的更新,它将提供一个具有集成功能的窗口,而不是多个对话框:
python Copy code
import sys
import os
import json
import logging
import requests
import pickle
from datetime import datetime
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QMessageBox, QScrollArea, QFrame, QInputDialog,
QGridLayout, QGraphicsDropShadowEffect, QDesktopWidget,
QLineEdit, QFormLayout, QComboBox, QSpacerItem, QSizePolicy)
from PyQt5.QtGui import QFont, QIcon, QPixmap, QFontDatabase, QColor, QBrush, QPalette
from PyQt5.QtCore import Qt, QSize
import subprocess
import webbrowser
# 定义日志路径和配置信息
SAVE_DIR = "./saves/players"
CONFIG_DIR = "./config/software/"
ELEMENT_COLOR_FILE = os.path.join(CONFIG_DIR, "elementcolor.json")
PATHS_MAPPING_FILE = os.path.join(CONFIG_DIR, "pathsmapping.json")
# 设置日志记录
log_dir = "./logs/"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_filename = f"srtool_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(os.path.join(log_dir, log_filename), encoding='utf-8')
])
# 加载元素颜色配置
def load_element_colors():
if not os.path.exists(ELEMENT_COLOR_FILE):
logging.error(f"Element color configuration file not found: {ELEMENT_COLOR_FILE}")
return {}
with open(ELEMENT_COLOR_FILE, 'r', encoding='utf-8') as f:
element_colors = json.load(f)
logging.debug(f"Loaded element colors: {element_colors}")
return element_colors
# 加载命途映射配置
def load_paths_mapping():
if not os.path.exists(PATHS_MAPPING_FILE):
logging.error(f"Paths mapping configuration file not found: {PATHS_MAPPING_FILE}")
return {}
with open(PATHS_MAPPING_FILE, 'r', encoding='utf-8') as f:
paths_mapping = json.load(f)
logging.debug(f"Loaded paths mapping: {paths_mapping}")
return paths_mapping
# 角色详细信息窗口类
class CharacterDetailWindow(QWidget):
def __init__(self, character, element_colors, paths_mapping):
super().__init__()
self.character = character
self.element_colors = element_colors
self.paths_mapping = paths_mapping
self.initUI()
def initUI(self):
self.setWindowTitle(f"{self.character['name']} - Detailed Information")
self.showMaximized()
# 设置窗口的背景图片
self.set_background()
# 创建主布局
main_layout = QVBoxLayout(self)
main_layout.setContentsMargins(0, 0, 0, 0)
# 创建一个QScrollArea
scroll_area = QScrollArea(self)
scroll_area.setWidgetResizable(True)
scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
# 创建一个容器小部件,并将其放置在scroll area中
container = QWidget()
scroll_area.setWidget(container)
# 在容器小部件上设置布局
layout = QVBoxLayout(container)
layout.setContentsMargins(50, 50, 50, 50)
# 添加角色立绘
splashart_path = f"image/splashart/{self.character['id']}.png"
splashart_pixmap = QPixmap(splashart_path).scaled(768, 768, Qt.KeepAspectRatio, Qt.SmoothTransformation)
splashart_label = QLabel(self)
splashart_label.setPixmap(splashart_pixmap)
# 添加命途符号
path_name = self.character['path']['name'].lower()
path_icon_key = self.paths_mapping.get(path_name, None)
if path_icon_key:
path_icon_path = f"image/path/{path_icon_key}.png"
path_pixmap = QPixmap(path_icon_path).scaled(128, 128, Qt.KeepAspectRatio, Qt.SmoothTransformation)
path_icon_label = QLabel(splashart_label)
path_icon_label.setPixmap(path_pixmap)
path_icon_label.move(10, 10)
layout.addWidget(splashart_label, alignment=Qt.AlignLeft | Qt.AlignTop)
# 将scroll_area加入主布局
main_layout.addWidget(scroll_area)
def set_background(self):
# 设置固定背景图片
palette = self.palette()
background_pixmap = QPixmap("image/gui/background.jpeg").scaled(self.size(), Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)
palette.setBrush(QPalette.Window, QBrush(background_pixmap))
self.setPalette(palette)
def resizeEvent(self, event):
# 调整背景图片大小以覆盖整个窗口
self.set_background()
super().resizeEvent(event)
# 主应用程序类
class HSRToolApp(QWidget):
def __init__(self):
super().__init__()
self.current_data = None
self.current_player = None
self.element_colors = load_element_colors()
self.paths_mapping = load_paths_mapping()
self.initUI()
def initUI(self):
self.setWindowTitle("HSR Toolkit")
self.setWindowIcon(QIcon("image/gui/icon.ico"))
self.setGeometry(0, 0, 800, 600)
self.showMaximized()
main_layout = QVBoxLayout(self)
# 创建模拟选项面板
simulation_panel = QFrame(self)
simulation_layout = QFormLayout(simulation_panel)
simulation_panel.setFrameShape(QFrame.StyledPanel)
simulation_panel.setFrameShadow(QFrame.Raised)
# 角色和武器信息输入
self.role_input = QLineEdit()
self.weapon_input = QLineEdit()
# 输入框
self.items_input = QLineEdit()
self.initial_role_pulls_input = QLineEdit()
self.initial_weapon_pulls_input = QLineEdit()
# 大保底选择
self.major_pity_role_input = QComboBox()
self.major_pity_role_input.addItems(["否", "是"])
self.major_pity_weapon_input = QComboBox()
self.major_pity_weapon_input.addItems(["否", "是"])
# 添加到布局中
simulation_layout.addRow("所需限定角色数:", self.role_input)
simulation_layout.addRow("所需限定武器数:", self.weapon_input)
simulation_layout.addRow("拥有道具数量:", self.items_input)
simulation_layout.addRow("角色池初始抽数:", self.initial_role_pulls_input)
simulation_layout.addRow("武器池初始抽数:", self.initial_weapon_pulls_input)
simulation_layout.addRow("角色池大保底:", self.major_pity_role_input)
simulation_layout.addRow("武器池大保底:", self.major_pity_weapon_input)
# 模拟按钮
run_simulation_button = QPushButton("运行模拟计算")
run_simulation_button.clicked.connect(self.run_simulation)
simulation_layout.addWidget(run_simulation_button)
# 将模拟面板添加到主布局
main_layout.addWidget(simulation_panel)
# 结果显示
self.result_label = QLabel("", self)
main_layout.addWidget(self.result_label)
# 添加随人机交互按钮
button_layout = QHBoxLayout()
self.cmd_button = QPushButton("Open CMD")
self.ticket_simulator_button = QPushButton("Open Ticket Simulator")
self.cmd_button.clicked.connect(self.open_cmd)
self.ticket_simulator_button.clicked.connect(self.open_ticket_simulator)
button_layout.addWidget(self.cmd_button)
button_layout.addWidget(self.ticket_simulator_button)
main_layout.addLayout(button_layout)
self.setLayout(main_layout)
def run_simulation(self):
# 收集用户输入并启动模拟
role_count = int(self.role_input.text())
weapon_count = int(self.weapon_input.text())
items = int(self.items_input.text())
initial_role_pulls = int(self.initial_role_pulls_input.text())
initial_weapon_pulls = int(self.initial_weapon_pulls_input.text())
major_pity_role = self.major_pity_role_input.currentText() == "是"
major_pity_weapon = self.major_pity_weapon_input.currentText() == "是"
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-simulate",
str(role_count), str(weapon_count), str(items),
str(initial_role_pulls), str(initial_weapon_pulls),
str(int(major_pity_role)), str(int(major_pity_weapon))],
capture_output=True, text=True)
output = result.stdout.strip()
self.result_label.setText(f"Simulation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
def open_cmd(self):
os.system("start cmd")
logging.info("Opened CMD")
def open_ticket_simulator(self):
reply = QMessageBox.question(self, "Visit Ticket Simulator",
"Would you like to open the wish simulator?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
webbrowser.open("https://hsr.wishsimulator.app/")
logging.info("Opened ticket simulator")
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("image/gui/icon.ico"))
window = HSRToolApp()
window.show()
sys.exit(app.exec_())
解释
C++ 代码 :
更新了 simulatePull 函数以正确处理武器池。
增加了四星分布的计算逻辑,包括出五星时四星的顺延。
calculateAveragePulls 函数计算了期望抽数、四星数和所需星琼数。
Python 代码 :
结合了所有输入参数为一个中心综合窗口。
使用 QFormLayout 提供清晰的用户界面,用来输入模拟参数。
提供按钮进行模拟计算并显示结果,采用 QLabel 显示返回的数值。
确保C++程序编译为 ratecalc.exe,放置在 expansions 目录下,并且有执行权限。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <string>
// 独立模拟角色池或武器池的抽卡
bool simulatePull(bool& guaranteed, int& pullCount, int poolType, bool majorPity, int& fourStarStreak, int& fourStars) {
const double baseRate = 0.006;
const double baseRateFourStar = 0.10;
const int pityStart = (poolType == 1) ? 73 : 63;
const int hardPity = (poolType == 1) ? 90 : 80;
const double rateIncrease = 0.062;
double pullRate = baseRate;
if (pullCount >= pityStart) {
pullRate += (pullCount - pityStart) * rateIncrease;
}
bool gotGold = (pullCount >= hardPity - 1) || (static_cast<double>(std::rand()) / RAND_MAX) < pullRate;
if (gotGold) {
pullCount = 0; // 出金重置抽数
fourStarStreak = 0; // 出金时也要重置四星连续抽数
// 金上本保底,星顺次延至下次
fourStarStreak = ((fourStarStreak + 1) % 10 == 0) ? 1 : fourStarStreak;
if (guaranteed || (majorPity) ||
(static_cast<double>(std::rand()) / RAND_MAX) < ((poolType == 1) ? 0.5 : 0.75)) {
guaranteed = false;
return true; // 获取限定物品
} else {
guaranteed = true;
return false; // 非限定
}
} else {
if ((fourStarStreak++ % 10 == 0) || (static_cast<double>(std::rand()) / RAND_MAX) < baseRateFourStar) {
fourStars++;
fourStarStreak = 0; // 四星出现,重置连续抽
}
pullCount += 1;
}
return false;
}
double calculateAveragePulls(int roleCount, int weaponCount, int& fourStarCount) {
int totalPulls = 0;
int totalFourStars = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = false, guaranteedWeapon = false;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = 0, weaponPullCount = 0;
int fourStarStreakRole = 0, fourStarStreakWeapon = 0;
int fourStars = 0;
while (roleObtained < roleCount || weaponObtained < weaponCount) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, false, fourStarStreakRole, fourStars)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, false, fourStarStreakWeapon, fourStars)) {
weaponObtained++;
}
pulls++;
}
}
totalPulls += pulls;
totalFourStars += fourStars;
}
fourStarCount = totalFourStars;
return static_cast<double>(totalPulls) / 10000.0;
}
double simulateWithItems(int roleCount, int weaponCount, int items, int initialRolePulls, int initialWeaponPulls, bool majorPityRole, bool majorPityWeapon) {
int successfulSimulations = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = majorPityRole, guaranteedWeapon = majorPityWeapon;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = initialRolePulls, weaponPullCount = initialWeaponPulls;
int fourStarStreakRole = 0, fourStarStreakWeapon = 0;
int fourStars = 0;
while (pulls < items) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, majorPityRole, fourStarStreakRole, fourStars)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount && pulls < items) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, majorPityWeapon, fourStarStreakWeapon, fourStars)) {
weaponObtained++;
}
pulls++;
}
if (roleObtained >= roleCount && weaponObtained >= weaponCount) {
successfulSimulations++;
break;
}
}
}
return static_cast<double>(successfulSimulations) / 10000.0 * 100.0; // 返回百分比
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <function> <parameters>..." << std::endl;
return 1;
}
std::srand(std::time(0)); // 设置随机种子
std::string function = argv[1];
if (function == "-average") {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " -average <roleCount> <weaponCount>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int fourStarCount = 0;
double averagePulls = calculateAveragePulls(roleCount, weaponCount, fourStarCount);
int starJades = static_cast<int>(std::ceil(averagePulls)) * 160;
std::cout << averagePulls << " " << fourStarCount / 10000.0 << " " << starJades << std::endl;
} else if (function == "-simulate") {
if (argc < 9) {
std::cerr << "Usage: " << argv[0] << " -simulate <roleCount> <weaponCount> <items> <initialRolePulls> <initialWeaponPulls> <majorPityRole> <majorPityWeapon>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int items = std::stoi(argv[4]);
int initialRolePulls = std::stoi(argv[5]);
int initialWeaponPulls = std::stoi(argv[6]);
bool majorPityRole = std::stoi(argv[7]);
bool majorPityWeapon = std::stoi(argv[8]);
double successRate = simulateWithItems(roleCount, weaponCount, items, initialRolePulls, initialWeaponPulls, majorPityRole, majorPityWeapon);
std::cout << successRate << "%" << std::endl;
} else {
std::cerr << "Invalid function specified." << std::endl;
return 1;
}
return 0;
}
完整的Python代码 以下是更新后的Python代码,其中包括一个更大的UI,以处理两个功能,确保所有功能都被实现和展示。
python Copy code
import sys
import os
import logging
import subprocess
from datetime import datetime
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QPushButton, QLabel,
QLineEdit, QFormLayout, QComboBox, QMessageBox, QHBoxLayout)
from PyQt5.QtGui import QIcon
# 设置日志记录
log_dir = "./logs/"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_filename = f"srtool_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(os.path.join(log_dir, log_filename), encoding='utf-8')
])
class HSRToolApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("HSR Toolkit")
self.setWindowIcon(QIcon("image/gui/icon.ico"))
self.setGeometry(0, 0, 800, 600)
self.showMaximized()
main_layout = QVBoxLayout(self)
# 模拟平均抽数面板
self.average_panel = QFrame(self)
average_layout = QFormLayout(self.average_panel)
self.average_panel.setFrameShape(QFrame.StyledPanel)
self.average_panel.setFrameShadow(QFrame.Raised)
self.avg_role_input = QLineEdit()
self.avg_weapon_input = QLineEdit()
average_layout.addRow("所需限定角色数(平均):", self.avg_role_input)
average_layout.addRow("所需限定武器数(平均):", self.avg_weapon_input)
run_average_button = QPushButton("运行平均抽数计算")
run_average_button.clicked.connect(self.run_average_calculator)
average_layout.addWidget(run_average_button)
main_layout.addWidget(self.average_panel)
# 模拟抽卡面板
self.simulation_panel = QFrame(self)
simulation_layout = QFormLayout(self.simulation_panel)
self.simulation_panel.setFrameShape(QFrame.StyledPanel)
self.simulation_panel.setFrameShadow(QFrame.Raised)
# 角色和武器信息输入
self.role_input = QLineEdit()
self.weapon_input = QLineEdit()
# 模拟输入框
self.items_input = QLineEdit()
self.initial_role_pulls_input = QLineEdit()
self.initial_weapon_pulls_input = QLineEdit()
# 大保底选择
self.major_pity_role_input = QComboBox()
self.major_pity_role_input.addItems(["否", "是"])
self.major_pity_weapon_input = QComboBox()
self.major_pity_weapon_input.addItems(["否", "是"])
# 添加到布局中
simulation_layout.addRow("所需限定角色数:", self.role_input)
simulation_layout.addRow("所需限定武器数:", self.weapon_input)
simulation_layout.addRow("拥有道具数量:", self.items_input)
simulation_layout.addRow("角色池初始抽数:", self.initial_role_pulls_input)
simulation_layout.addRow("武器池初始抽数:", self.initial_weapon_pulls_input)
simulation_layout.addRow("角色池大保底:", self.major_pity_role_input)
simulation_layout.addRow("武器池大保底:", self.major_pity_weapon_input)
# 模拟按钮
run_simulation_button = QPushButton("运行模拟计算")
run_simulation_button.clicked.connect(self.run_simulation)
simulation_layout.addWidget(run_simulation_button)
# 添加到主布局
main_layout.addWidget(self.simulation_panel)
# 结果显示
self.result_label = QLabel("", self)
main_layout.addWidget(self.result_label)
# 操作按钮
button_layout = QHBoxLayout()
self.cmd_button = QPushButton("Open CMD")
self.ticket_simulator_button = QPushButton("Open Ticket Simulator")
self.cmd_button.clicked.connect(self.open_cmd)
self.ticket_simulator_button.clicked.connect(self.open_ticket_simulator)
button_layout.addWidget(self.cmd_button)
button_layout.addWidget(self.ticket_simulator_button)
main_layout.addLayout(button_layout)
def run_average_calculator(self):
# 收集平均抽数输入参数并启动计算
role_count = int(self.avg_role_input.text())
weapon_count = int(self.avg_weapon_input.text())
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-average", str(role_count), str(weapon_count)],
capture_output=True, text=True)
output = result.stdout.strip()
self.result_label.setText(f"Average Simulation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
def run_simulation(self):
# 收集用户输入并启动模拟
role_count = int(self.role_input.text())
weapon_count = int(self.weapon_input.text())
items = int(self.items_input.text())
initial_role_pulls = int(self.initial_role_pulls_input.text())
initial_weapon_pulls = int(self.initial_weapon_pulls_input.text())
major_pity_role = self.major_pity_role_input.currentText() == "是"
major_pity_weapon = self.major_pity_weapon_input.currentText() == "是"
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-simulate",
str(role_count), str(weapon_count), str(items),
str(initial_role_pulls), str(initial_weapon_pulls),
str(int(major_pity_role)), str(int(major_pity_weapon))],
capture_output=True, text=True)
output = result.stdout.strip()
self.result_label.setText(f"Simulation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
def open_cmd(self):
os.system("start cmd")
logging.info("Opened CMD")
def open_ticket_simulator(self):
reply = QMessageBox.question(self, "Visit Ticket Simulator",
"Would you like to open the wish simulator?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
webbrowser.open("https://hsr.wishsimulator.app/")
logging.info("Opened ticket simulator")
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("image/gui/icon.ico"))
window = HSRToolApp()
window.show()
sys.exit(app.exec_())
关键点说明:
C++ 代码 :
修正了在进五星保底时的四星顺延逻辑。
simulatePull处理抽卡逻辑,calculateAveragePulls处理功能一的计算,simulateWithItems处理功能二。
main函数根据输入参数选择执行功能一还是功能二。
Python 代码 :
通过UI中两个不同的面板,分别实现功能一和功能二。
run_average_calculator处理平均抽卡次数及相关数据的计算。
run_simulation处理模拟特定卡池条件下的抽卡概率。
执行时请确保ratecalc.exe正确放置于脚本路径中的expansions目录下,并具备执行权限。
import sys
import os
import json
import logging
import requests
import pickle
from datetime import datetime
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QMessageBox, QScrollArea, QFrame, QInputDialog,
QGridLayout, QGraphicsDropShadowEffect, QDesktopWidget,
QLineEdit, QFormLayout, QComboBox, QSizePolicy)
from PyQt5.QtGui import QFont, QIcon, QPixmap, QFontDatabase, QColor, QBrush, QPalette
from PyQt5.QtCore import Qt, QSize
import subprocess
import webbrowser
# 定义日志路径和配置信息
SAVE_DIR = "./saves/players"
CONFIG_DIR = "./config/software/"
ELEMENT_COLOR_FILE = os.path.join(CONFIG_DIR, "elementcolor.json")
PATHS_MAPPING_FILE = os.path.join(CONFIG_DIR, "pathsmapping.json")
# 设置日志记录
log_dir = "./logs/"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_filename = f"srtool_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(os.path.join(log_dir, log_filename), encoding='utf-8')
])
def load_element_colors():
if not os.path.exists(ELEMENT_COLOR_FILE):
logging.error(f"Element color configuration file not found: {ELEMENT_COLOR_FILE}")
return {}
with open(ELEMENT_COLOR_FILE, 'r', encoding='utf-8') as f:
element_colors = json.load(f)
logging.debug(f"Loaded element colors: {element_colors}")
return element_colors
def load_paths_mapping():
if not os.path.exists(PATHS_MAPPING_FILE):
logging.error(f"Paths mapping configuration file not found: {PATHS_MAPPING_FILE}")
return {}
with open(PATHS_MAPPING_FILE, 'r', encoding='utf-8') as f:
paths_mapping = json.load(f)
logging.debug(f"Loaded paths mapping: {paths_mapping}")
return paths_mapping
class CharacterDetailWindow(QWidget):
def __init__(self, character, element_colors, paths_mapping):
super().__init__()
self.character = character
self.element_colors = element_colors
self.paths_mapping = paths_mapping
self.initUI()
def initUI(self):
self.setWindowTitle(f"{self.character['name']} - Detailed Information")
self.showMaximized()
self.set_background()
main_layout = QVBoxLayout(self)
main_layout.setContentsMargins(0, 0, 0, 0)
scroll_area = QScrollArea(self)
scroll_area.setWidgetResizable(True)
scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
container = QWidget()
scroll_area.setWidget(container)
layout = QVBoxLayout(container)
layout.setContentsMargins(50, 50, 50, 50)
splashart_path = f"image/splashart/{self.character['id']}.png"
splashart_pixmap = QPixmap(splashart_path).scaled(768, 768, Qt.KeepAspectRatio, Qt.SmoothTransformation)
splashart_label = QLabel(self)
splashart_label.setPixmap(splashart_pixmap)
path_name = self.character['path']['name'].lower()
path_icon_key = self.paths_mapping.get(path_name, None)
if path_icon_key:
path_icon_path = f"image/path/{path_icon_key}.png"
path_pixmap = QPixmap(path_icon_path).scaled(128, 128, Qt.KeepAspectRatio, Qt.SmoothTransformation)
path_icon_label = QLabel(splashart_label)
path_icon_label.setPixmap(path_pixmap)
path_icon_label.move(10, 10)
layout.addWidget(splashart_label, alignment=Qt.AlignLeft | Qt.AlignTop)
main_layout.addWidget(scroll_area)
def set_background(self):
palette = self.palette()
background_pixmap = QPixmap("image/gui/background.jpeg").scaled(self.size(), Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)
palette.setBrush(QPalette.Window, QBrush(background_pixmap))
self.setPalette(palette)
def resizeEvent(self, event):
self.set_background()
super().resizeEvent(event)
class HSRToolApp(QWidget):
def __init__(self):
super().__init__()
self.current_data = None
self.current_player = None
self.element_colors = load_element_colors()
self.paths_mapping = load_paths_mapping()
self.initUI()
def initUI(self):
self.setWindowTitle("HSR Toolkit")
self.setWindowIcon(QIcon("image/gui/icon.ico"))
self.setGeometry(0, 0, 1200, 800)
self.showMaximized()
main_layout = QVBoxLayout(self)
# 面板1: 计算平均抽数
average_panel = QFrame(self)
average_layout = QFormLayout(average_panel)
average_panel.setFrameShape(QFrame.StyledPanel)
average_panel.setFrameShadow(QFrame.Raised)
self.avg_role_input = QLineEdit()
self.avg_weapon_input = QLineEdit()
average_layout.addRow("所需限定角色数(平均):", self.avg_role_input)
average_layout.addRow("所需限定武器数(平均):", self.avg_weapon_input)
run_average_button = QPushButton("运行平均抽数计算")
run_average_button.clicked.connect(self.run_average_calculator)
average_layout.addWidget(run_average_button)
main_layout.addWidget(average_panel)
# 面板2: 模拟抽卡
simulation_panel = QFrame(self)
simulation_layout = QFormLayout(simulation_panel)
simulation_panel.setFrameShape(QFrame.StyledPanel)
simulation_panel.setFrameShadow(QFrame.Raised)
self.role_input = QLineEdit()
self.weapon_input = QLineEdit()
self.items_input = QLineEdit()
self.initial_role_pulls_input = QLineEdit()
self.initial_weapon_pulls_input = QLineEdit()
self.major_pity_role_input = QComboBox()
self.major_pity_role_input.addItems(["否", "是"])
self.major_pity_weapon_input = QComboBox()
self.major_pity_weapon_input.addItems(["否", "是"])
simulation_layout.addRow("所需限定角色数:", self.role_input)
simulation_layout.addRow("所需限定武器数:", self.weapon_input)
simulation_layout.addRow("拥有道具数量:", self.items_input)
simulation_layout.addRow("角色池初始抽数:", self.initial_role_pulls_input)
simulation_layout.addRow("武器池初始抽数:", self.initial_weapon_pulls_input)
simulation_layout.addRow("角色池大保底:", self.major_pity_role_input)
simulation_layout.addRow("武器池大保底:", self.major_pity_weapon_input)
run_simulation_button = QPushButton("运行模拟计算")
run_simulation_button.clicked.connect(self.run_simulation)
simulation_layout.addWidget(run_simulation_button)
main_layout.addWidget(simulation_panel)
self.result_label = QLabel("", self)
main_layout.addWidget(self.result_label)
button_layout = QHBoxLayout()
self.cmd_button = QPushButton("Open CMD")
self.ticket_simulator_button = QPushButton("Open Ticket Simulator")
self.cmd_button.clicked.connect(self.open_cmd)
self.ticket_simulator_button.clicked.connect(self.open_ticket_simulator)
button_layout.addWidget(self.cmd_button)
button_layout.addWidget(self.ticket_simulator_button)
main_layout.addLayout(button_layout)
self.setLayout(main_layout)
def run_average_calculator(self):
role_count = int(self.avg_role_input.text())
weapon_count = int(self.avg_weapon_input.text())
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-average", str(role_count), str(weapon_count)],
capture_output=True, text=True)
output = result.stdout.strip()
self.result_label.setText(f"Average Simulation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
def run_simulation(self):
role_count = int(self.role_input.text())
weapon_count = int(self.weapon_input.text())
items = int(self.items_input.text())
initial_role_pulls = int(self.initial_role_pulls_input.text())
initial_weapon_pulls = int(self.initial_weapon_pulls_input.text())
major_pity_role = self.major_pity_role_input.currentText() == "是"
major_pity_weapon = self.major_pity_weapon_input.currentText() == "是"
exe_path = os.path.join("expansions", "ratecalc.exe")
try:
result = subprocess.run([exe_path, "-simulate",
str(role_count), str(weapon_count), str(items),
str(initial_role_pulls), str(initial_weapon_pulls),
str(int(major_pity_role)), str(int(major_pity_weapon))],
capture_output=True, text=True)
output = result.stdout.strip()
self.result_label.setText(f"Simulation Output: {output}")
except Exception as e:
QMessageBox.critical(self, "Execution Failed", f"Error running ratecalc.exe: {e}")
def open_cmd(self):
os.system("start cmd")
logging.info("Opened CMD")
def open_ticket_simulator(self):
reply = QMessageBox.question(self, "Visit Ticket Simulator",
"Would you like to open the wish simulator?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
webbrowser.open("https://hsr.wishsimulator.app/")
logging.info("Opened ticket simulator")
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("image/gui/icon.ico"))
window = HSRToolApp()
window.show()
sys.exit(app.exec_())
解释
UI设计 :
使用垂直布局,将两个功能面板(平均计算和模拟抽卡)进行布局排列。
每个功能面板通过 QFormLayout 布局,包含必要的输入项和操作按钮。
功能实现 :
run_average_calculator负责计算平均抽数,并更新结果标签。
run_simulation用于模拟抽卡,并更新结果标签。
请确保 ratecalc.exe 文件编译好且在 expansions 目录下运行。这个程序提供一个完整的UI,并为每个功能提供一个面板和相应的操作。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <string>
// 独立模拟角色池或武器池的抽卡
bool simulatePull(bool& guaranteed, int& pullCount, int poolType, bool majorPity, int& fourStarStreak, int& fourStars) {
const double baseRate = 0.006;
const double baseRateFourStar = 0.10;
const int rolePityStart = 73;
const int roleHardPity = 90;
const int weaponPityStart = 63;
const int weaponHardPity = 80;
int pityStart = (poolType == 1) ? rolePityStart : weaponPityStart;
int hardPity = (poolType == 1) ? roleHardPity : weaponHardPity;
double rateIncrease = 0.062;
double pullRate = baseRate;
if (pullCount >= pityStart) {
pullRate += (pullCount - pityStart) * rateIncrease;
}
bool gotGold = (pullCount >= hardPity - 1) || (static_cast<double>(std::rand()) / RAND_MAX) < pullRate;
if (gotGold) {
pullCount = 0; // 出金重置抽数
fourStarStreak = 0; // 出金时也要重置四星连续抽数
// 金色物品的处理(在5星优先时,4星顺延到下一次)
fourStarStreak = ((fourStarStreak + 1) % 10 == 0) ? 1 : fourStarStreak;
if (guaranteed || (majorPity) ||
(static_cast<double>(std::rand()) / RAND_MAX) < ((poolType == 1) ? 0.5 : 0.75)) {
guaranteed = false;
return true; // 获取限定物品
} else {
guaranteed = true;
return false; // 非限定
}
} else {
bool gotFourStar = ((fourStarStreak++ % 10 == 0) || (static_cast<double>(std::rand()) / RAND_MAX) < baseRateFourStar);
if (gotFourStar) {
fourStars++;
fourStarStreak = 0; // 四星出现,重置连续抽
}
pullCount += 1;
}
return false;
}
double calculateAveragePulls(int roleCount, int weaponCount, int& fourStarCount) {
int totalPulls = 0;
int totalFourStars = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = false, guaranteedWeapon = false;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = 0, weaponPullCount = 0;
int fourStarStreakRole = 0, fourStarStreakWeapon = 0;
int fourStars = 0;
while (roleObtained < roleCount || weaponObtained < weaponCount) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, false, fourStarStreakRole, fourStars)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, false, fourStarStreakWeapon, fourStars)) {
weaponObtained++;
}
pulls++;
}
}
totalPulls += pulls;
totalFourStars += fourStars;
}
fourStarCount = totalFourStars;
return static_cast<double>(totalPulls) / 10000.0;
}
double simulateWithItems(int roleCount, int weaponCount, int items, int initialRolePulls, int initialWeaponPulls, bool majorPityRole, bool majorPityWeapon) {
int successfulSimulations = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = majorPityRole, guaranteedWeapon = majorPityWeapon;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = initialRolePulls, weaponPullCount = initialWeaponPulls;
int fourStarStreakRole = 0, fourStarStreakWeapon = 0;
int fourStars = 0;
while (pulls < items) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, majorPityRole, fourStarStreakRole, fourStars)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount && pulls < items) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, majorPityWeapon, fourStarStreakWeapon, fourStars)) {
weaponObtained++;
}
pulls++;
}
if (roleObtained >= roleCount && weaponObtained >= weaponCount) {
successfulSimulations++;
break;
}
}
}
return static_cast<double>(successfulSimulations) / 10000.0 * 100.0;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <function> <parameters>..." << std::endl;
return 1;
}
std::srand(std::time(0)); // 设置随机种子
std::string function = argv[1];
if (function == "-average") {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " -average <roleCount> <weaponCount>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int fourStarCount = 0;
double averagePulls = calculateAveragePulls(roleCount, weaponCount, fourStarCount);
int starJades = static_cast<int>(std::ceil(averagePulls)) * 160;
std::cout << averagePulls << " " << fourStarCount / 10000.0 << " " << starJades << std::endl;
} else if (function == "-simulate") {
if (argc < 9) {
std::cerr << "Usage: " << argv[0] << " -simulate <roleCount> <weaponCount> <items> <initialRolePulls> <initialWeaponPulls> <majorPityRole> <majorPityWeapon>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int items = std::stoi(argv[4]);
int initialRolePulls = std::stoi(argv[5]);
int initialWeaponPulls = std::stoi(argv[6]);
bool majorPityRole = std::stoi(argv[7]);
bool majorPityWeapon = std::stoi(argv[8]);
double successRate = simulateWithItems(roleCount, weaponCount, items, initialRolePulls, initialWeaponPulls, majorPityRole, majorPityWeapon);
std::cout << successRate << "%" << std::endl;
} else {
std::cerr << "Invalid function specified." << std::endl;
return 1;
}
return 0;
}
解释
抽卡机制更新 :
武器池和角色池的保底和大保底分别处理。
通过 poolType 区分角色池和武器池,1 为角色池,2 为武器池。
四星系统 :
确保上方C++代码经过编译,且生成的可执行文件路径正确,以便在Python程序中调用。接下来,将会为Python进行UI更新。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <string>
// 独立模拟角色池或武器池的抽卡
bool simulatePull(bool& guaranteed, int& pullCount, int poolType, bool majorPity) {
const double baseRate = 0.006;
const int rolePityStart = 73;
const int roleHardPity = 90;
const int weaponPityStart = 63;
const int weaponHardPity = 80;
int pityStart = (poolType == 1) ? rolePityStart : weaponPityStart;
int hardPity = (poolType == 1) ? roleHardPity : weaponHardPity;
double rateIncrease = 0.062;
double pullRate = baseRate;
if (pullCount >= pityStart) {
pullRate += (pullCount - pityStart) * rateIncrease;
}
bool gotGold = (pullCount >= hardPity - 1) || (static_cast<double>(std::rand()) / RAND_MAX) < pullRate;
if (gotGold) {
pullCount = 0; // 出金重置抽数
double guaranteedRate = (poolType == 1) ? 0.5 : 0.75; // 角色池和武器池的初始概率
if (guaranteed || (majorPity) ||
(static_cast<double>(std::rand()) / RAND_MAX) < guaranteedRate) {
guaranteed = false; // 重置非限定保底
return true; // 获取限定物品
} else {
guaranteed = true; // 下一次必定限定
return false; // 非限定
}
} else {
pullCount += 1;
}
return false;
}
double calculateAveragePulls(int roleCount, int weaponCount) {
int totalPulls = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = false, guaranteedWeapon = false;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = 0, weaponPullCount = 0;
while (roleObtained < roleCount || weaponObtained < weaponCount) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, false)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, false)) {
weaponObtained++;
}
pulls++;
}
}
totalPulls += pulls;
}
return static_cast<double>(totalPulls) / 10000.0;
}
double simulateWithItems(int roleCount, int weaponCount, int items, int initialRolePulls, int initialWeaponPulls, bool majorPityRole, bool majorPityWeapon) {
int successfulSimulations = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = majorPityRole, guaranteedWeapon = majorPityWeapon;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = initialRolePulls, weaponPullCount = initialWeaponPulls;
while (pulls < items) {
if (roleObtained < roleCount && simulatePull(guaranteedRole, rolePullCount, 1, majorPityRole)) {
roleObtained++;
}
pulls++;
if (roleObtained == roleCount && pulls < items) {
if (simulatePull(guaranteedWeapon, weaponPullCount, 2, majorPityWeapon)) {
weaponObtained++;
}
pulls++;
}
if (roleObtained >= roleCount && weaponObtained >= weaponCount) {
successfulSimulations++;
break;
}
}
}
return static_cast<double>(successfulSimulations) / 10000.0 * 100.0;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <function> <parameters>..." << std::endl;
return 1;
}
std::srand(std::time(0)); // 设置随机种子
std::string function = argv[1];
if (function == "-average") {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " -average <roleCount> <weaponCount>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
double averagePulls = calculateAveragePulls(roleCount, weaponCount);
int starJades = static_cast<int>(std::ceil(averagePulls)) * 160;
std::cout << averagePulls << " " << starJades << std::endl;
} else if (function == "-simulate") {
if (argc < 9) {
std::cerr << "Usage: " << argv[0] << " -simulate <roleCount> <weaponCount> <items> <initialRolePulls> <initialWeaponPulls> <majorPityRole> <majorPityWeapon>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int items = std::stoi(argv[4]);
int initialRolePulls = std::stoi(argv[5]);
int initialWeaponPulls = std::stoi(argv[6]);
bool majorPityRole = std::stoi(argv[7]);
bool majorPityWeapon = std::stoi(argv[8]);
double successRate = simulateWithItems(roleCount, weaponCount, items, initialRolePulls, initialWeaponPulls, majorPityRole, majorPityWeapon);
std::cout << successRate << "%" << std::endl;
} else {
std::cerr << "Invalid function specified." << std::endl;
return 1;
}
return 0;
}
关键更新和解释:
概率处理修正 :角色池使用50%的概率获取限定,武器池使用75%的概率。没有获取限定时设置guaranteed为true,确保下一次出金必定为限定。
参数处理 :通过poolType区分角色池和武器池,并根据不同池子的规则设置出金概率。
确保随机数生成和概率评估逻辑正确应用于两个独立的池子。
请确认用g++或其他C++编译器编译生成的二进制文件能与Python代码正确协作。接下来在Python中结合这段C++逻辑实现应用程序的更新。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <string>
// 模拟角色池的抽卡
bool simulateRolePull(bool& guaranteedRole, int& rolePullCount, bool majorPity) {
const double baseRate = 0.006;
const int pityStart = 73;
const int hardPity = 90;
const double rateIncrease = 0.062;
double pullRate = baseRate;
if (rolePullCount >= pityStart) {
pullRate += (rolePullCount - pityStart) * rateIncrease;
}
bool gotGold = (rolePullCount >= hardPity - 1) || (static_cast<double>(std::rand()) / RAND_MAX) < pullRate;
if (gotGold) {
rolePullCount = 0;
double guaranteedRate = 0.5; // 角色池初始概率
if (guaranteedRole || majorPity || (static_cast<double>(std::rand()) / RAND_MAX) < guaranteedRate) {
guaranteedRole = false;
return true; // 获取限定物品
} else {
guaranteedRole = true; // 下次必定限定
return false; // 非限定
}
} else {
rolePullCount += 1;
}
return false;
}
// 模拟武器池的抽卡
bool simulateWeaponPull(bool& guaranteedWeapon, int& weaponPullCount, bool majorPity) {
const double baseRate = 0.006;
const int pityStart = 63;
const int hardPity = 80;
const double rateIncrease = 0.062;
double pullRate = baseRate;
if (weaponPullCount >= pityStart) {
pullRate += (weaponPullCount - pityStart) * rateIncrease;
}
bool gotGold = (weaponPullCount >= hardPity - 1) || (static_cast<double>(std::rand()) / RAND_MAX) < pullRate;
if (gotGold) {
weaponPullCount = 0;
double guaranteedRate = 0.75; // 武器池初始概率
if (guaranteedWeapon || majorPity || (static_cast<double>(std::rand()) / RAND_MAX) < guaranteedRate) {
guaranteedWeapon = false;
return true; // 获取限定物品
} else {
guaranteedWeapon = true; // 下次必定限定
return false; // 非限定
}
} else {
weaponPullCount += 1;
}
return false;
}
double calculateAveragePulls(int roleCount, int weaponCount) {
int totalPulls = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = false, guaranteedWeapon = false;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = 0, weaponPullCount = 0;
// 先抽角色池
while (roleObtained < roleCount) {
if (simulateRolePull(guaranteedRole, rolePullCount, false)) {
roleObtained++;
}
pulls++;
}
// 再抽武器池
while (weaponObtained < weaponCount) {
if (simulateWeaponPull(guaranteedWeapon, weaponPullCount, false)) {
weaponObtained++;
}
pulls++;
}
totalPulls += pulls;
}
return static_cast<double>(totalPulls) / 10000.0;
}
double simulateWithItems(int roleCount, int weaponCount, int items, int initialRolePulls, int initialWeaponPulls, bool majorPityRole, bool majorPityWeapon) {
int successfulSimulations = 0;
for (int i = 0; i < 10000; ++i) {
int pulls = 0;
bool guaranteedRole = majorPityRole, guaranteedWeapon = majorPityWeapon;
int roleObtained = 0, weaponObtained = 0;
int rolePullCount = initialRolePulls, weaponPullCount = initialWeaponPulls;
// 先抽角色池
while (roleObtained < roleCount && pulls < items) {
if (simulateRolePull(guaranteedRole, rolePullCount, majorPityRole)) {
roleObtained++;
}
pulls++;
}
// 再抽武器池
while (weaponObtained < weaponCount && pulls < items) {
if (simulateWeaponPull(guaranteedWeapon, weaponPullCount, majorPityWeapon)) {
weaponObtained++;
}
pulls++;
}
if (roleObtained >= roleCount && weaponObtained >= weaponCount) {
successfulSimulations++;
}
}
return static_cast<double>(successfulSimulations) / 10000.0 * 100.0;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <function> <parameters>..." << std::endl;
return 1;
}
std::srand(std::time(0)); // 设置随机种子
std::string function = argv[1];
if (function == "-average") {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " -average <roleCount> <weaponCount>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
double averagePulls = calculateAveragePulls(roleCount, weaponCount);
int starJades = static_cast<int>(std::ceil(averagePulls)) * 160;
std::cout << averagePulls << " " << starJades << std::endl;
} else if (function == "-simulate") {
if (argc < 9) {
std::cerr << "Usage: " << argv[0] << " -simulate <roleCount> <weaponCount> <items> <initialRolePulls> <initialWeaponPulls> <majorPityRole> <majorPityWeapon>" << std::endl;
return 1;
}
int roleCount = std::stoi(argv[2]);
int weaponCount = std::stoi(argv[3]);
int items = std::stoi(argv[4]);
int initialRolePulls = std::stoi(argv[5]);
int initialWeaponPulls = std::stoi(argv[6]);
bool majorPityRole = std::stoi(argv[7]);
bool majorPityWeapon = std::stoi(argv[8]);
double successRate = simulateWithItems(roleCount, weaponCount, items, initialRolePulls, initialWeaponPulls, majorPityRole, majorPityWeapon);
std::cout << successRate << "%" << std::endl;
} else {
std::cerr << "Invalid function specified." << std::endl;
return 1;
}
return 0;
}
关键改动
角色池和武器池拆分 :分别用simulateRolePull和simulateWeaponPull两个独立的函数来模拟角色池和武器池。
出金逻辑清晰化 :角色池的初始概率为50%,武器池的初始概率为75%。当未获得限定时,guaranteed设置为true,确保下次必定获得限定。
独立计数 :角色和武器的抽取过程独立计算,不会互相影响,履行实际游戏中的抽卡独立性。
这段代码应该能用于模拟角色池和武器池下达成条件的次数和成功率。接下来,我们将更新Python代码以便更好地与此代码接口。