繁体   English   中英

Python类程序使用类程序模拟两个骰子的掷骰

[英]Python program using class programs to simulate the roll of two dice

我的程序应该模拟两个骰子,但是我遇到了问题。 这是我的代码:

import random

#Dice class simulates both a single and two dice being rolled
#sideup data attribute with 'one'

class Dice:
    #sideup data attribute with 'one'

    def __init__(self):
        self.sideup='one'
    def __init__(self):
        self.twosides='one and two'

 #the toss method generates a random number
 #in the range of 1 through 6.


    def toss(self):
        if random.randint(1,6)==1:
            self.sideup='one'
        elif random.randint(1,6)==2:
            self.sideup='two'
        elif random.randint(1,6)==3:
            self.sideup='three'
        elif random.randint(1,6)==4:
            self.sideup='four'
        elif random.randint(1,6)==5:
            self.sideup='five'
        else:
            self.sideup='six'
    def get_sideup(self):
        return self.sideup
    def doubletoss(self):
        if random.randint(1,6)==1 and random.randint(1,6)==2:
            self.twosides='one and two'
        elif random.randint(1,6)==1 and random.randint(1,6)==3:
            self.twosides='one and three'
        elif random.randint(1,6)==1 and random.randint(1,6)==4:
            self.twosides='one and four'
        elif random.randint(1,6)==1 and random.randint(1,6)==5:
            self.twosides='one and five'
        elif random.randint(1,6)==1 and random.randint(1,6)==6:
            self.twosides='one and six'
        elif random.randint(1,6)==1 and random.randint(1,6)==1:
            self.twosides='one and one'
    def get_twosides(self):
        return self.twosides






#main function
def main():
    #create an object from the Dice class
    my_dice=Dice()


    #Display the siide of the dice is factory
   print('This side is up',my_dice.get_sideup())

    #toss the dice
    print('I am tossing the dice')
    my_dice.toss()

    #toss two dice
    print('I am tossing two die')
    my_dice.doubletoss()

   #Display the side of the dice that is facing up
    print('this side is up:',my_dice.get_sideup())

    #display both dices with the sides of the dice up
    print('the sides of the two dice face up are:',my_dice.get_twosides())



main()

这是我运行程序时的输出:

“跟踪(最近一次通话结束):文件“ C:/Users/Pentazoid/Desktop/PythonPrograms/DiceClass.py”,行79(位于main()文件“ C:/Users/Pentazoid/Desktop/PythonPrograms/DiceClass.py ”,在主打印中的第61行,“此面朝上”,my_dice.get_sideup())文件“ C:/Users/Pentazoid/Desktop/PythonPrograms/DiceClass.py”,在第32行,在get_sideup中返回self.sideup

AttributeError:“骰子”对象没有属性“ sideup”

我究竟做错了什么?

您有两种初始化方法。 第二个替换第一个,否定您对sideup的定义。

改成:

def __init__(self):
    self.sideup='one'
    self.twosides='one and two'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM