|
发表于 2024-4-4 21:24:16
|
显示全部楼层
是的,`self.code`这一行的作用是将代码存储在一个列表中,每个元素代表一行代码。你可以在其中添加需要执行的代码行。
对于删除代码行的部分,确实将所有代码放在一个列表中可能会导致不现实和混乱。为了解决这个问题,您可以设定一个最大行数,并通过从中取随机数的方式来选择要删除的行数。
以下是修改后的代码示例:
- import random
- from PySide6.QtWidgets import QApplication, QMainWindow, QMessageBox
- class MainWindow(QMainWindow):
- def __init__(self):
- super().__init__()
- self.setWindowTitle("Code Randomizer")
- self.counter = 0
- self.max_uses = 100
- self.code = [
- "print('Hello, World!')",
- "x = 10",
- "y = 20",
- "result = x + y",
- "print(result)"
- ]
- self.show_warning = False
- self.randomize_code()
-
- def randomize_code(self):
- if self.counter >= self.max_uses and not self.show_warning:
- self.show_warning_dialog()
- self.show_warning = True
-
- if self.counter < self.max_uses:
- self.counter += 1
-
- # 设定要删除的行数和行数范围
- lines_to_delete = random.randint(1, min(3, len(self.code)))
- line_indices = random.sample(range(len(self.code)), lines_to_delete)
-
- # 根据行数范围删除代码行
- for index in sorted(line_indices, reverse=True):
- self.code.pop(index)
-
- # 执行代码
- for line in self.code:
- exec(line)
-
- def show_warning_dialog(self):
- msg_box = QMessageBox()
- msg_box.setWindowTitle("警告")
- msg_box.setText("您已经到达使用次数上限!")
- msg_box.setIcon(QMessageBox.Warning)
- msg_box.setStandardButtons(QMessageBox.Ok)
- msg_box.exec_()
- if __name__ == "__main__":
- app = QApplication()
- window = MainWindow()
- app.exec()
复制代码
此次更新后,我们将代码存储在一个列表中,然后通过生成要删除的行数和从中选择要删除的行数的行索引,以确保实际删除的行数不超过列表的长度。之后,我们根据行索引删除相应的代码行,并执行剩余的代码行。
请注意,这只是一个简单的示例,以演示如何从中删除随机行。对于复杂的代码和处理逻辑,可能需要更加详细和精确的操作。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|