掷骰子
# die.py 骰子类
from random import randint
class Die():
"""表示一个骰子的类"""
def __init__(self, num_sides=6):
"""骰子默认为六面"""
self.num_sides = num_sides
def roll(self):
"""返回一个位于1和骰子面数之间的随机值(整数)"""
return randint(1, self.num_sides)
# die_visual.py 可视化骰子
import pygal
from die import Die
# 创建一个D6
die_1 = Die()
die_2 = Die()
# 掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(1000):
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)
frequencies.append(frequency)
# 可视化结果
hist = pygal.Bar() # 创建pygal.Bar()实例以创建条形图
hist.title = 'Results of rolling two D6 1000 times.'
hist.x_labels = [str(x) for x in range(2, 13)]
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'
hist.add('D6 + D6', frequencies) # add(label, [values])
hist.render_to_file('die_visual_double.svg')