私はゲーム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の動作方法や、クラス(など)を使用してこの種のプログラミングを高速化する方法がわからないため、動作させることができません。主な問題は、辞書の同じ場所を上書きすることがよくあることです(辞書を使用している場合)。
書き直されたプレイヤークラス:
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
そして最後に、プレーヤーのスコアを表示します。
for player_id, player in plyarr.items():
print player.dispScore()
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加