我正在尝试创建游戏Snakeeyes的一个版本,它将在程序开始时接受n,n是玩家的数量。
到目前为止,我已经设法做到这一点:
import random
def rollDice():
dice = random.randint(1, 6)
print "You rolled a", dice
return dice
def addUser(name):
name = player()
print name, "is a player"
class player():
score = 0
players = []
def __init__(self):
score = 0
player.score = score
def addScore(self, dice1, dice2):
if dice1 == 1 or dice2 == 1:
player.score = 0
if dice1 == 1 and dice2 == 1:
print "SNAKE EYES"
else:
player.score += dice1
player.score += dice2
return player.score
def dispScore(self):
return player.score
numbp = int(input("Please enter number of players \n"))
plyarr = dict()
for x in range(numbp):
plyarr[x] = player()
plyarr[x].addScore(rollDice(),rollDice())
for x in range(numbp):
print plyarr[x].score
然而,由于我对python如何工作的天真以及如何使用类(等)来加速这种编程,我无法使它工作。主要问题是它经常覆盖字典中的相同位置(如果我使用字典)。
答案 0 :(得分:0)
重写的球员类:
class player():
def __init__(self):
self.score = 0
self.players = []
def addScore(self, dice1, dice2):
if dice1 == 1 or dice2 == 1:
player.score = 0
if dice1 == 1 and dice2 == 1:
print "SNAKE EYES"
else:
self.score += dice1
self.score += dice2
return self.score
def dispScore(self):
return self.score
def __str__(self):
return '<a description of the current object>'
根据你的评论,我假设你正在考虑将球员存放在字典中的方式;您可以按照以下方式执行此操作(对原始代码进行了少量更改)
numbp = int(input("Please enter number of players \n"))
plyarr = dict()
for x in range(numbp):
current_player = player()
current_player.addScore(rollDice(),rollDice())
playarr[x] = current_player
最后,展示你的球员&#39;分数:
for player_id, player in plyarr.items():
print player.dispScore()