Using Pygal to simulate roll dice
Pygal Official website: http://www.pygal.org/Create a die class
From random Import Randint class Die (): "" "" "
is the class of a dice" ""
def __init__ (self,num_sides = 6): "" "
dice defaults to 6 sides" " "
self.num_sides = num_sides
def roll (self):" "
returns a random value between 1 and the number of dice" "" Return
Randint (1,self.num_ Sides
Generate a result histogram
From die import die
import Pygal
#创建一个D6 a D10
die_1 = die ()
die_2 = Die (a)
#掷几次骰子 and store the results in a list
results = []
#5000次 for
roll_num in range (5000): Result
= Die_1.roll () + die_2.roll ()
Results.append (Result)
#分析结果
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for Value in range (2,max_result+1):
frequency = Results.count (value) #count方法统计列表中某一项出现的次数
frequencies.append (frequency)
#对结果进行可视化
hist = Pygal. Bar ()
hist.title = "Results of rolling a D6 and a D10 50000 times"
hist.x_labels = [' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ', ', ', ', ', ', ', ', ', ', '
hist.x_title = ' result '
hist.y_title = ' Frequency of result '
Hist.add ("D6+D10", frequencies)
#渲染为svg文件
hist.render_to_file (' die_visual.svg ')