掷骰子游戏 - 无法附加历史结果

问题描述 投票:0回答:1

我需要创建骰子游戏,它有规则:

Your solution should support from 1 to 5 dice.
The dice can have from 1 to 100 sides.
The solution should be able to simulate throwing the dice one or more times, returning the values of the dice.
The solution needs to store the information about the last 100 throws.

一切都很清楚,除了最后一个标准(存储有关 100 次抛出的信息),这是我的代码:

import random

class DiceEngine:
    def __init__(self):
        self.history = []

    def roll_dice(self, num_dice=1, sides=6, num_rolls=1):
        """
        Simulate rolling the dice.

        Args:
            num_dice (int): Number of dice to roll.
            sides (int): Number of sides on each die.
            num_rolls (int): Number of times to roll the dice.

        Returns:
            list: List of lists containing the values of each dice for each roll.
        """
        if num_dice < 1 or num_dice > 5:
            raise ValueError("Number of dice should be between 1 and 5.")

        if sides < 1 or sides > 100:
            raise ValueError("Number of sides should be between 1 and 100.")

        rolls = []
        for i in range(num_rolls):
            values = []
            for i in range(num_dice):
                values.append(random.randint(1, sides))
            rolls.append(values)

        self._update_history(rolls)
        return rolls

    def get_last_100_rolls(self):
        """
        Get information about the last 100 throws.

        Returns:
            list: List of lists containing the values of each dice for each of the last 100 throws.
        """
        return self.history[-min(len(self.history), 100):]

    def _update_history(self, rolls):
        self.history.extend(rolls)
        self.history = self.history[-100:]

dice_engine = DiceEngine()
result = dice_engine.roll_dice(num_dice=3, sides=20, num_rolls=5)
print("Dice Rolls:", result)
print("Last 100 Rolls:", dice_engine.get_last_100_rolls())

由于输出中的某种原因,我没有将所有先前的抛出附加到当前的抛出,我只得到当前的抛出结果。谁能告诉我,代码哪里错了?

python append
1个回答
0
投票

没有定义存储最后 100 个抛出的变量,当您运行程序时,仅显示当前值。您必须使用某种东西来存储数据,无论是在数据库还是文件中。

最简单的解决方案是每次运行程序时打开要写入的文件,如果文件超过 100 行,请重新重写。

    def get_last_100_rolls(self):
    
    file_name = 'your_file.txt'
    history = self.history

    # Check if the file exists
    if not os.path.exists(file_name):
        # If the file doesn't exist, create it and write an initial value (e.g., an empty string)
        with open(file_name, 'w') as file:
            file.write('')

    with open(file_name, 'r') as file:
        lines = file.readlines()

    # If there are more than 100 lines, overwrite the file
    if len(lines) > 100:
        with open(file_name, 'w') as file:
            # Write the values from the 'history' array to the file
            file.write(' '.join(map(str, history)) + '\n')

    else:
        with open(file_name, 'a') as file:
            file.write(' '.join(map(str, history)) + '\n')

    with open('your_file.txt', 'r') as file:
        # Read the contents of the file
        file_contents = file.read()

    # Print the contents

    return file_contents
© www.soinside.com 2019 - 2024. All rights reserved.