簡體   English   中英

如何將類數據存儲在數組中,並根據需要調用這些數據?

[英]How do I store class data in an array and recall this data as needed?

我正在嘗試創建游戲Snakeeyes的一個版本,該版本將在程序開始時使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM