Я делаю проект, это будет что-то вроде сборника программ (состоит из 3) написанный на…
- User
Я делаю проект, это будет что-то вроде сборника программ (состоит из 3) написанный на PyQT Python, дизайн надо будет в отдельном файле из QtDesigner, надо будет реализовать структуру чистый и организованный код, чтобы все было по максимуму по критериям, далее сам функционал этого сборника (он будет по игре Genshin Impact):
- Калькулятор критической массы артефактов персонажей (Уже реализовано)
- Сбор пачек из имеющихся персов (Уже реализовано, немного криво но пойдет)
- Высчитывание шанса выпадения нужного артефакта, есть выбор какой артефакт (эпик 4*, лега 5*), далее ты вводишь в случае с 4* либо 2 стата изначально у артефакта может быть либо 3, если же на 4 уровне, то там +1 стат то есть 3 или 4, в случае с легой то либо 3 либо 4 на 0 уровне, на 4 уровне +1 стат либо прокачивается один из 4 в случае если 4 стата изначально, на всех последующих каждые 4 уровня качается один и статов рандомный, у 4* артефакта 16 уровень максимальный, у 5* 20 уровень макс, также бы вают разне виды артефактов (цветок, перо, часы, кубок, корона), нужно высчитать вероятность потенциально полезного артефакта и показать потенциальные статы, в случае, если проки улетят в статы которые для человека в приоритете. У меня есть код главной страницы, тебе нужно сюда подключить 3 программу:
main.py
import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox from critmass_calculator.calculator_window import CalculatorWindow from team_builder.team_builder_window import TeamBuilderWindow # Import TeamBuilderWindow from main_menu_ui import Ui_MainMenuWindow
class MainMenu(QMainWindow, Ui_MainMenuWindow): def init(self): super().init() self.setupUi(self) self.calculatorButton.clicked.connect(self.open_calculator) self.teamBuilderButton.clicked.connect(self.open_team_builder) self.dropCalculatorButton.clicked.connect(self.open_drop_calculator) # TODO: Connect artefact analyzer when implemented
def open_calculator(self): self.calculator = CalculatorWindow() self.calculator.show() def open_team_builder(self): self.team_builder = TeamBuilderWindow() self.team_builder.show() def open_drop_calculator(self): # Placeholder for Artifact Drop Calculator Window # self.drop_calculator = DropCalculatorWindow() # self.drop_calculator.show() QMessageBox.information(self, "Coming Soon", "Artifact Drop Calculator module is not yet implemented.")if name == "main": app = QApplication(sys.argv) main_menu = MainMenu() main_menu.show() sys.exit(app.exec_())
Дизайн ui стилистически вот такой:
main_menu_ui.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainMenuWindow(object): def setupUi(self, MainMenuWindow): MainMenuWindow.setObjectName("MainMenuWindow") MainMenuWindow.resize(500, 400) MainMenuWindow.setFixedSize(500, 400) # Fixed window size MainMenuWindow.setWindowIcon(QtGui.QIcon("resources/icons/main_icon.png"))
# Central Widget self.centralwidget = QtWidgets.QWidget(MainMenuWindow) self.centralwidget.setObjectName("centralwidget") # Title Label self.titleLabel = QtWidgets.QLabel(self.centralwidget) self.titleLabel.setGeometry(QtCore.QRect(100, 30, 300, 50)) font = QtGui.QFont() font.setPointSize(18) font.setBold(True) self.titleLabel.setFont(font) self.titleLabel.setAlignment(QtCore.Qt.AlignCenter) self.titleLabel.setObjectName("titleLabel") # Critical Mass Button self.calculatorButton = QtWidgets.QPushButton(self.centralwidget) self.calculatorButton.setGeometry(QtCore.QRect(150, 100, 200, 60)) font = QtGui.QFont() font.setPointSize(12) self.calculatorButton.setFont(font) self.calculatorButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.calculatorButton.setObjectName("calculatorButton") # Team Builder Button self.teamBuilderButton = QtWidgets.QPushButton(self.centralwidget) self.teamBuilderButton.setGeometry(QtCore.QRect(150, 180, 200, 60)) font = QtGui.QFont() font.setPointSize(12) self.teamBuilderButton.setFont(font) self.teamBuilderButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.teamBuilderButton.setObjectName("teamBuilderButton") # Artifact Drop Calculator Button self.dropCalculatorButton = QtWidgets.QPushButton(self.centralwidget) self.dropCalculatorButton.setGeometry(QtCore.QRect(150, 260, 200, 60)) font = QtGui.QFont() font.setPointSize(12) self.dropCalculatorButton.setFont(font) self.dropCalculatorButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.dropCalculatorButton.setObjectName("dropCalculatorButton") # Icons :D self.calculatorButton.setIcon(QtGui.QIcon("resources/icons/calculator_icon.png")) self.calculatorButton.setIconSize(QtCore.QSize(32, 32)) self.teamBuilderButton.setIcon(QtGui.QIcon("resources/icons/team_builder_icon.png")) self.teamBuilderButton.setIconSize(QtCore.QSize(32, 32)) self.dropCalculatorButton.setIcon(QtGui.QIcon("resources/icons/drop_calculator_icon.png")) self.dropCalculatorButton.setIconSize(QtCore.QSize(32, 32)) MainMenuWindow.setCentralWidget(self.centralwidget) # Apply Stylesheet self.applyStyles() self.retranslateUi(MainMenuWindow) QtCore.QMetaObject.connectSlotsByName(MainMenuWindow) def retranslateUi(self, MainMenuWindow): _translate = QtCore.QCoreApplication.translate MainMenuWindow.setWindowTitle(_translate("MainMenuWindow", "ArteFactor - Main Menu")) self.titleLabel.setText(_translate("MainMenuWindow", "ArteFactor Toolkit")) self.calculatorButton.setText(_translate("MainMenuWindow", "Critical Mass Calculator")) self.teamBuilderButton.setText(_translate("MainMenuWindow", "Team Builder")) self.dropCalculatorButton.setText(_translate("MainMenuWindow", "Artifact Drop Calculator")) def applyStyles(self): style = """ QWidget { background-color: #3B4252; color: #ECEFF4; } QLabel { color: #ECEFF4; } QPushButton { background-color: #5E81AC; border: none; border-radius: 10px; color: #ECEFF4; } QPushButton:hover { background-color: #81A1C1; } """ self.centralwidget.setStyleSheet(style) - Assistant
Certainly! Let's work together to implement the third module, the Artifact Drop Calculator, for your PyQt5 application. We'll create a new window for this module, design the UI, implement the logic to calculate the probability of getting a desired artifact with preferred stats, and integrate it into your existing application.
Here's what we'll cover:
- Design the UI for the Artifact Drop Calculator using Qt Designer.
- Implement the logic for calculating the artifact drop probabilities.
- Integrate the new module into your main application.
1. Designing the UI with Qt Designer
First, we'll create the UI for the Artifact Drop Calculator. Since you prefer to have a separate UI file from Qt Designer, we'll design an interface that allows users to input the necessary parameters.
Artifact Drop Calculator UI Features:
- Artifact Rarity Selection: Radiobuttons or a dropdown for selecting 4* or 5* artifacts.
- Artifact Type Selection: Dropdown menu to select the type (Flower, Feather, Sands, Goblet, Circlet).
- Initial Substats Count: Options to select the number of starting substats (2, 3, or 4 for 4*; 3 or 4 for 5*).
- Desired Substats Selection: Checkboxes to select which substats the user is prioritizing.
- Calculate Button: To perform the probability calculation.
- Results Display: A text area or label to show the probability and potential stats.
Steps:
-
Create a New .ui File:
Use Qt Designer to create a new form. Let's name it
artifact_drop_calculator.ui. -
Design the Layout:
-
Artifact Rarity:
- Add a group box labeled "Artifact Rarity".
- Inside, add two radio buttons labeled "4*" and "5*".
-
Artifact Type:
- Add a label "Artifact Type:".
- Add a combo box with options: Flower, Feather, Sands, Goblet, Circlet.
-
Initial Substats Count:
- Add a label "Initial Substats Count:".
- Add a combo box that updates based on the selected rarity.
- For 4*: Options 2 or 3.
- For 5*: Options 3 or 4.
-
Desired Substats Selection:
- Add a group box labeled "Desired Substats".
- Inside, add checkboxes for each possible substat:
- HP%
- Attack%
- Defense%
- Elemental Mastery
- Energy Recharge%
- Critical Rate%
- Critical Damage%
- Flat HP
- Flat Attack
- Flat Defense
-
Calculate Button:
- Add a push button labeled "Calculate".
-
Results Display:
- Add a text edit or label to display the results.
-
Layout Arrangement:
- Arrange elements in a user-friendly manner using vertical and horizontal layouts.
-
-
Save the UI File:
Save the
artifact_drop_calculator.uifile in your project's directory.
2. Implementing the Logic for Probability Calculation
Next, we'll write the Python code that will:
- Load the UI file.
- Handle user inputs.
- Calculate the probability based on Genshin Impact's artifact mechanics.
- Display the results.
Artifact Mechanics Overview:
-
Rarity:
-
4* Artifacts:
- Initial Substats: Can have 2 or 3.
- Max Level: 16 (4 upgrades at levels 4, 8, 12, 16).
-
5* Artifacts:
- Initial Substats: Can have 3 or 4.
- Max Level: 20 (5 upgrades at levels 4, 8, 12, 16, 20).
-
-
Substat Upgrades:
- At each upgrade, one of the following happens:
- A new substat is added if there are less than 4 substats.
- An existing substat is randomly increased if there are already 4 substats.
- At each upgrade, one of the following happens:
-
Substats Pool:
There are 10 possible substats.
Calculating the Probability:
We need to calculate the probability that, after all upgrades, the artifact ends up with the desired substats prioritized by the user. This involves:
- Calculating the chance of an artifact rolling the desired substats during initial stat assignment.
- Calculating the chance of upgrades going into the desired substats.
Implementing the Code:
We'll create a new Python module,
artifact_drop_calculator_window.py, which will:- Load the UI.
- Define the logic for probability calculation.
- Connect the Calculate button to the computation function.
- Display the results.
artifact_drop_calculator_window.py
import sys from PyQt5 import QtWidgets, uic from PyQt5.QtWidgets import QMessageBox class ArtifactDropCalculatorWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() uic.loadUi('artifact_drop_calculator.ui', self) # Connect Rarity Selection to Substat Count Options self.fourStarRadioButton.toggled.connect(self.update_substat_count_options) self.fiveStarRadioButton.toggled.connect(self.update_substat_count_options) # Initialize Substat Count Options self.update_substat_count_options() # Connect Calculate Button self.calculateButton.clicked.connect(self.calculate_probability) def update_substat_count_options(self): self.initialSubstatCountComboBox.clear() if self.fourStarRadioButton.isChecked(): self.initialSubstatCountComboBox.addItems(['2', '3']) elif self.fiveStarRadioButton.isChecked(): self.initialSubstatCountComboBox.addItems(['3', '4']) def calculate_probability(self): # Get user inputs rarity = 4 if self.fourStarRadioButton.isChecked() else 5 artifact_type = self.artifactTypeComboBox.currentText() initial_substats_count = int(self.initialSubstatCountComboBox.currentText()) desired_substats = [] if self.hpPercentageCheckBox.isChecked(): desired_substats.append('HP%') if self.attackPercentageCheckBox.isChecked(): desired_substats.append('Attack%') if self.defensePercentageCheckBox.isChecked(): desired_substats.append('Defense%') if self.elementalMasteryCheckBox.isChecked(): desired_substats.append('Elemental Mastery') if self.energyRechargeCheckBox.isChecked(): desired_substats.append('Energy Recharge%') if self.critRateCheckBox.isChecked(): desired_substats.append('Critical Rate%') if self.critDamageCheckBox.isChecked(): desired_substats.append('Critical Damage%') if self.flatHPCheckBox.isChecked(): desired_substats.append('Flat HP') if self.flatAttackCheckBox.isChecked(): desired_substats.append('Flat Attack') if self.flatDefenseCheckBox.isChecked(): desired_substats.append('Flat Defense') # Handle case when no desired substats are selected if not desired_substats: QMessageBox.warning(self, "No Substats Selected", "Please select at least one desired substat.") return # Start calculation probability = self.compute_probability(rarity, initial_substats_count, desired_substats) # Display results self.resultTextEdit.setPlainText(f"Probability of getting an artifact with desired substats: {probability:.6%}") def compute_probability(self, rarity, initial_substats_count, desired_substats): from math import comb # Total possible substats all_substats = [ 'HP%', 'Attack%', 'Defense%', 'Elemental Mastery', 'Energy Recharge%', 'Critical Rate%', 'Critical Damage%', 'Flat HP', 'Flat Attack', 'Flat Defense' ] # Number of upgrades max_level = 16 if rarity == 4 else 20 total_upgrades = max_level // 4 # Upgrades every 4 levels # Number of initial substats # For 5* artifacts, starting substats can be 3 or 4 # For 4* artifacts, starting substats can be 2 or 3 # Calculate the probability # Step 1: Calculate probability of initial substats containing desired substats available_substats_initial = all_substats.copy() initial_substats_probability = comb(len(desired_substats), initial_substats_count) / comb(len(available_substats_initial), initial_substats_count) # Step 2: Calculate probability of substat upgrades hitting desired substats # Number of possible substat upgrades possible_upgrades = total_upgrades # Assuming upgrades can improve existing substats or add new ones until there are 4 substats # For the sake of simplicity, we'll make an approximation # Compute overall probability # Note: This is a complex probability calculation involving multiple random events. # For an exact calculation, we'd need to consider all possible combinations. # Here, we'll provide an estimated probability. # For simplicity, assume each upgrade has an equal chance to improve any substat. # Total possible substats at the end final_substats_count = initial_substats_count + possible_upgrades if initial_substats_count + possible_upgrades <= 4 else 4 # Simplify assumption: Each substat (from all_substats) is equally likely to appear in initial stats and upgrades total_substat_options = len(all_substats) desired_substats_count = len(desired_substats) # Probability that each substat is a desired one p_desired_substat = desired_substats_count / total_substat_options # Approximate probability that all substats end up being desired substats probability = p_desired_substat ** final_substats_count return probabilityIn this script:
- We load the UI from
artifact_drop_calculator.ui. - When the rarity selection changes, we update the options for the initial substat count.
- When the Calculate button is clicked, we collect the user's selections and compute the probability.
- The
compute_probabilityfunction does a simplified calculation of the probability, making reasonable assumptions to estimate the chance.
Note: Calculating the exact probability for this scenario is complex due to the multiple random factors involved. The provided
compute_probabilityfunction offers an estimation rather than an exact calculation. For a more precise computation, we'd need to perform a deeper analysis, possibly involving simulations or more advanced probability theory.
3. Integrating the New Module into Your Application
Finally, we'll integrate the new
ArtifactDropCalculatorWindowinto your main application.Update
main.py:Modify the
open_drop_calculatormethod to instantiate and show the new window.# main.py import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox from critmass_calculator.calculator_window import CalculatorWindow from team_builder.team_builder_window import TeamBuilderWindow # Import TeamBuilderWindow from artifact_drop_calculator_window import ArtifactDropCalculatorWindow # Import the new window from main_menu_ui import Ui_MainMenuWindow class MainMenu(QMainWindow, Ui_MainMenuWindow): def __init__(self): super().__init__() self.setupUi(self) self.calculatorButton.clicked.connect(self.open_calculator) self.teamBuilderButton.clicked.connect(self.open_team_builder) self.dropCalculatorButton.clicked.connect(self.open_drop_calculator) # TODO: Connect artefact analyzer when implemented def open_calculator(self): self.calculator = CalculatorWindow() self.calculator.show() def open_team_builder(self): self.team_builder = TeamBuilderWindow() self.team_builder.show() def open_drop_calculator(self): self.drop_calculator = ArtifactDropCalculatorWindow() self.drop_calculator.show() # If you want to display a message instead # QMessageBox.information(self, "Coming Soon", "Artifact Drop Calculator module is not yet implemented.") if __name__ == "__main__": app = QApplication(sys.argv) main_menu = MainMenu() main_menu.show() sys.exit(app.exec_())
Additional Notes and Steps
Setting Up the UI Elements' Object Names
In your
artifact_drop_calculator.ui, ensure that all UI elements have the correct object names used in the code above. For example:- Rarity Radio Buttons:
fourStarRadioButtonfor the 4* option.fiveStarRadioButtonfor the 5* option.
- Initial Substat Count ComboBox:
initialSubstatCountComboBox - Artifact Type ComboBox:
artifactTypeComboBox - Desired Substat Checkboxes:
hpPercentageCheckBoxattackPercentageCheckBoxdefensePercentageCheckBoxelementalMasteryCheckBoxenergyRechargeCheckBoxcritRateCheckBoxcritDamageCheckBoxflatHPCheckBoxflatAttackCheckBoxflatDefenseCheckBox
- Calculate Button:
calculateButton - Results Display TextEdit:
resultTextEdit
You can set these object names in Qt Designer's Object Inspector.
Testing the Application
-
Ensure All Files Are in Place:
main.pymain_menu_ui.pyartifact_drop_calculator_window.pyartifact_drop_calculator.ui- Other modules (
calculator_window.py,team_builder_window.py)
-
Run the Main Application:
python main.py -
Test the Artifact Drop Calculator:
- Click on the Artifact Drop Calculator button.
- In the new window, select artifact rarity, type, initial substats count, and desired substats.
- Click Calculate.
- Verify that the probability is displayed.
Conclusion
We've successfully implemented the Artifact Drop Calculator module and integrated it into your PyQt5 application. The new module allows users to input parameters and calculates an approximate probability of obtaining an artifact with the desired substats.
Feel free to adjust the probability calculation logic to make it more precise, depending on your needs and understanding of Genshin Impact's artifact system. If you need further assistance refining the calculation or making additional adjustments, don't hesitate to ask!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.