Joakim Dahl Joakim Dahl - 3 months ago 15
Python Question

Yahtzee, using a dictionary instead of list of attributes

So my issue is that currently I have code for my yahtzee (I will not post all of the code, but the important stuff is looking like this (and it works):

from terminaltables import AsciiTable

class Player:
def __init__(self,name):
self.name=name
self.ones=0
self.twos=0
self.threes=0
self.fours=0
self.fives=0
self.sixs=0
self.abovesum=0
self.bonus=0
self.onepair=0
self.twopair=0
self.threepair=0
self.fourpair=0
self.smalladder=0
self.bigladder=0
self.house=0
self.chance=0
self.yatzy=0
self.totalsum=0

def welcome():
global spelarlista
spelarlista=[]
print("Welcome to the yahtzee game!")
players = int(input("How many players: "))
rounds=0
while not players==rounds:
player=input("What is your name?: ")
rounds=rounds+1
spelarlista.append(Player(player))
table_data = [["Name"] + spelarlista,
['Ones'] + [player.ones for player in spelarlista],
['Twos'] + [player.twos for player in spelarlista],
['Threes'] + [player.threes for player in spelarlista],
['Fours'] + [player.fours for player in spelarlista],
['Fives'] + [player.fives for player in spelarlista],
['Sixs'] + [player.sixs for player in spelarlista]]
table = AsciiTable(table_data)
table.inner_row_border = True
print(table.table)
spelarlista[0].add()
welcome()


The issue right now is that I want to add a dictionary instead of all those self.ones, self.twos etc. If you take a look at my welcome method, you can see that I have
[player.ones for player in spelarlista]
and I need this to assign the players points, how can I fix so this work for a dictionary instead? The dictionary is neccesary for my next method, add, if you were curious!

Thanks in advance!

Answer
dict_names = ['ones', 'twos', ..., 'totalsum']
self.dict = {name:0 for name in dict_names}

and to access you'd use player.dict['fours'] instead if player.fours

Comments