我从教授那里收到了这个项目,但我无法让代码运行良好

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

包含代码说明的文件代码导出到的文件 这底部是我尝试创建的代码

import random

    class Die:
    def __init__(self, sides):
        self.sides = sides
        self.value = 1
    def roll(self):
        self.value = random.randrange(1, self.sides+1)
        return self.value

    class DiceBag:
        def __init__(self, dice_list):
            self.dice = dice_list
        def singleRoll(self, sides):
            die = next (x for x in self.dice if x.sides == sides)
        if die:
            return die.roll()
        else:
            return -1
        
    def mulitRoll(self, sides, num_rolls):
        die = next(i for i in self.dice if i.sides == sides)
        if die:
            return sum(die.roll() for _ in range (num_rolls))
        else:
            return -1
        

这是我为该项目所做的尝试,我对 python 和一般编码仍然相当陌生

python computer-science
1个回答
0
投票

据我所知,您应该将 str 方法添加到 Die 类中:

def __str__(self):
    return f"Die with {self.sides} sides, current value: {self.value}"

也在 DiceBag 类中:

def __str__(self):
    return f"DiceBag with {len(self.dice)} dice: " + ", ".join(str(die) for die in self.dice)

在 DiceBag 类中更改 None 的处理

 def __init__(self, dice_list=None):
    if dice_list is None:
        dice_list = []
    self.dice = dice_list

还添加addDie功能 def addDie(自身, 边): self.dice.append(骰子(面))

def singleRoll(self, sides):
    die = next((x for x in self.dice if x.sides == sides), None)
    if die:
        return die.roll()
    else:
        return -1

def multiRoll(self, sides, num_rolls):
    die = next((x for x in self.dice if x.sides == sides), None)
    if die:
        return sum(die.roll() for _ in range(num_rolls))
    else:
        return -1

这应该有效,或者您应该提供所需的输出。

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