骰子类游戏

时间:2019-01-07 16:13:07

标签: python class

我为一项运动而疯狂。我必须做一个骰子游戏,询问我们将有多少名玩家玩该游戏,将玩几轮以及要使用多少个骰子。然后,在第一轮掷骰子;如果玩家能够猜出一个骰子的数量,那么他为每个正确猜出的骰子都会得到一个分数;如果他没有得到正确的骰子,那只能减去一分。然后,我必须向每个球员展示他们的得分。

但是真正的问题是我必须使用类和对象,这才是真正的问题。

我不希望有任何评论说这是一些常规的事情,因为我对类和对象不是很好,他可以对这样的程序的想法发表评论,这会很棒。非常感谢

import random

class Dice:

    def __init__(self,num_players,num_rounds,num_dices):
        self.num_players=num_players
        self.num_rounds=num_rounds
        self.num_dices=num_dices

    def roll(self):
        self.number=random.randint(1,6)

    def __str__(self):
        return str(self.number)

def main():

    nPlayers=int(input('How many players? '))
    nRounds=int(input('How many rounds? '))
    nDices=int(input('How many dices will be used? '))
    game=Dice(nPlayers, nRounds, nDices)
    for i in range(nRounds):
        for j in range(nPlayers):
            game.roll()
            guess=int(input('Try guessing the number player'+str(j)+str(' ')))
main()

1 个答案:

答案 0 :(得分:0)

为了记录,我设法以自己想要的方式获得了该程序。如果有人进行相同的锻炼并需要帮助,就将其发布。谢谢大家!

在这里

随机导入

骰子类:

def __init__(self,num_players,num_rounds,num_dices):
    self.num_players=num_players
    self.num_rounds=num_rounds
    self.num_dices=num_dices
    self.value=random.randint(1,6)
    self.dic={}
    self.list=[]

def game(self):
    for i in range(self.num_rounds):
        for k in range(self.num_dices):
            self.value=random.randint(1,6)
            self.list.append(self.value)
        for j in range(self.num_players):
            guess=int(input('Try guessing the number player'+str(j)+str(' ')))
            if(guess not in self.list):
                if(j in self.dic.keys()):
                    self.dic[j]-=1
                else:
                    self.dic[j]=-1
            elif(guess in self.list):
                n=self.list.count(guess)
                if(j in self.dic.keys()):
                    self.dic[j]+=n
                else:
                    self.dic[j]=n

        print(self.list)
        self.list.clear()

def __str__(self):
    return str(self.dic)

def main():

nPlayers=int(input('How many players? '))
nRounds=int(input('How many rounds? '))
nDices=int(input('How many dices will be used? '))
game=Dice(nPlayers, nRounds, nDices)
game.game()
print(game)

main()