I just want to make a separate function in the dice class which would allow me to store every 'roll' in the list_of_rolls list in the 'rolls' function. so when 'rolls' is called it would display a list of every 'roll' executed (if any).
I tried using global but it didn't work (maybe i did it wrong), i also heard using global is a bad habit so if there is another way i wouldn't mind. my indents are proper it is just not shown here.
import random
class Dice:
def roll(self):
x = random.randint(1, 6)
y = random.randint(1, 6)
roll_list = (x, y)
return roll_list
def rolls(self):
list_of_rolls = []
final = list_of_rolls.append()
return final
There are a few ways you can do this. However I am just going to suggest the most straight forward way which is to use text file to store your history of rolls within the Dice class itself. Note that the con will be multiple instances of Dice will be accessing the same history file However this implementation may not be optimized, as everytime you roll a dice you are opening the file and appending new rolls to it. It may not be ideal if you need millions of rolls. That say I will leave it to you to better/optimize the solution.
import random
class Dice:
list_of_rolls = []
filename = "./roll_history.txt" # a textfile to store history of rolls
def __init__(self):
try: # just to check if file exists if not create one for storing
file = open(self.filename, "r")
except FileNotFoundError:
print("File not found")
file = open(self.filename, "x") #creates file
finally:
file.close()
with open(self.filename, 'r') as opened_file_object:
self.list_of_rolls = opened_file_object.read().splitlines()
print(self.list_of_rolls)
def roll(self):
x = random.randint(1, 6)
y = random.randint(1, 6)
roll_list = (x, y)
self.list_of_rolls.append(roll_list) # updates the array with latest roll
file = open(self.filename, 'a') # 'a' for appending new rolls
# I append a newline so that the rolls are more readable in the text file
file.write('(' + str(x) + ',' + str(y) + ')\n') # appends a newline
return roll_list
def rolls(self):
return self.list_of_rolls
print(Dice().roll()) # append 2 dice rolls here
print(Dice().roll())
print(Dice().rolls()) # you should see 2 dice rolls here
Dice() # you should be able to see past rolls