from random import randint
import pygal
class Die():
"""表示一個骰子的類"""
def __init__(self, num_sides=6):
"""骰子預設6面"""
self.num_sides = num_sides
def roll(self):
"""返回一個位於1和骰子面數之間的隨機值"""
return randint(1, self.num_sides)
# 投擲一個骰子
die_1 = Die()
print(die_1.roll())
results = []
for roll_num in range(100):
result = die_1.roll()
results.append(result)
print(results)
for num in range(1, 7):
print("面為%-2d的出現的次數為:%d)" % (num, results.count(num)))
# 投擲兩個骰子
die_1 = Die()
die_2 = Die()
# 擲幾次骰子,並將結果儲存在一個列表中
results = []
for roll_num in range(100):
result = die_1.roll() + die_2.roll()
results.append(result)
# 列印擲骰子的結果
print("1", results)
# 分析結果
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)
print("面為%-2d的出現的次數為:%d)" % (value, results.count(value)))
# 列印每個面出現的次數
print(frequencies)
# 對結果進行視覺化
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times"
hist.x_labels = [str(i) for i in range(2, 13)]
hist.x_tile = "Result"
hist.y_title = "Frequency of Result"
hist.add("D6+D6", frequencies)
hist.render_to_file("dice_visual.svg")
print("圖表製作成功")