bkoohy bkoohy - 2 months ago 10
Python Question

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

I'm trying to create a version of the game Snakeeyes, which will take in n at the start of the program, n being the number of players.

So far, I have managed to get this far:

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


However,I can't get it to work because of my naivety with how python works and how classes (etc) can be used to speed this sort of programming up. The main issue is that often it overwrites the same spot in the dictionary (if I use a dictionary).

Answer

Re written player class:

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>'

From your comment, I assume you are inquring about the way to store the players in a dictionary; you could do it as follows (did a small change to your original code)

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

And finally, display your players' scores:

for player_id, player in plyarr.items():
    print player.dispScore()
Comments