11""" Player class file """
22
3+ from collections import defaultdict
4+
35class Player (object ):
46 """Describe the player, his inventory, traits, position and history"""
57
68 def __init__ (self , state = None ):
79 self .state = state
8- self .items = {}
9- self .traits = {}
10- self .history = {}
10+ self .items = defaultdict ( lambda : 0 )
11+ self .traits = defaultdict ( lambda : 0 )
12+ self .history = defaultdict ( lambda : False )
1113
1214
1315 def save_to (self , filename ):
@@ -35,27 +37,27 @@ def set_traits(self, traits):
3537 def update_traits (self , traits ):
3638 """Update the players traits to reflect the parameter traits. (Adds to the previous value)"""
3739 for trait , value in traits .items ():
38- self .traits [trait ] = self . traits . get ( trait , 0 ) + value
40+ self .traits [trait ] += value
3941
4042
4143 def has_traits (self , traits ):
4244 """Return true if the player has all traits in parameter traits (equal or more)"""
4345 for trait , value in traits .items ():
44- if self .traits .get ( trait , 0 ) < value :
46+ if self .traits .get [ trait ] < value :
4547 return False
4648 return True
4749
4850
4951 def update_items (self , items : dict ):
5052 """Update the players inventory to reflect the parameter items. (Adds to the previous value)"""
5153 for item , count in items .items ():
52- self .items [item ] = max (self .items . get ( item , 0 ) + count , 0 ) # clamps value to zero if result is negative
54+ self .items [item ] = max (self .items [ item ] + count , 0 ) # clamps value to zero if result is negative
5355
5456
5557 def has_items (self , items : dict ):
5658 """Return true if the player has at least number of items specified in parameter items"""
5759 for item , count in items .items ():
58- if self .items . get ( item , 0 ) < count :
60+ if self .items [ item ] < count :
5961 return False
6062 return True
6163
@@ -69,7 +71,7 @@ def set_history(self, history: dict):
6971 def has_history (self , history : dict ):
7072 """Return true if all values in player history and in parameter are equal"""
7173 for story , value in history .items ():
72- if self .history . get ( story , 0 ) != value :
74+ if self .history [ story ] != value :
7375 return False
7476 return True
7577
0 commit comments