Simulation of rolling dice with Pygal

In this blog, we will learn to use the python visualization package Pygal to generate vector graphics files. Useful for charts that need to be displayed on screens of different sizes. Because they automatically scale to fit the viewer's screen.
.In
this project we will analyze the results of rolling a dice. Rolling a 6-sided regular dice has the same probability of outcome. But if two dice are rolled at the same time, some numbers are more likely to come up than others.
To determine which dots are most likely to occur, we generate a dataset representing the results of rolling a dice and draw a graph of the results.

Install Pygal

win + R -> cmd to open the command line window

Then enter the command:

python -m pip install --user pygal==1.7

insert image description here

OK is installed. keep going...

Pygal Gallery

Create the Die class

This class is used to simulate rolling a dice:
die.py

from random import randint

class Die():
    #一个模拟投掷筛子的类
    def __init__(self,num_sides=6):
        #骰子默认只有6面
        self.num_sides = num_sides
    
    def roll(self):
        #返回一个位于1和筛子面数之间的随机值
        return randint(1,self.num_sides)
        

About the init method of the Die class

Takes one optional parameter. When creating an instance of this class, if no parameters are specified, the number of faces defaults to 6. Instead, this value will be used to set the number of sides of the dice. The dice are named according to the number of sides, for example: 6 sides are named D6, 8 sides are named D8, and so on.

About the roll method of the Die class

This method uses the function randint() to return a random number between 1 and the number of faces. This function may return a start value of 1, an end value of num_sides, or any integer in between.

dice

Before using this class to create a diagram, throw a D6 sieve, print the result, and check that the result is reasonable:
die_visual.py

from die import Die

#创建一个D6
die = Die()

#将所投掷的几次筛子的结果存储到列表中
results =[]
for roll_num in range(10):
    result = die.roll()
    results.append(result)

print(results)

Results of rolling the dice 10 times:
insert image description here

analysis results

To analyze the results of rolling a D6 dice, we count the number of times each dot occurs:

die_visual.py:

from die import Die

#创建一个D6
die = Die()

#将所投掷的几次筛子的结果存储到列表中
results =[]
for roll_num in range(1000):
    result = die.roll()
    results.append(result)

#分析结果
frequencies = []
for value in range(1,die.num_sides+1):
    frequency = results.count(value)
    frequencies.append(frequency)
print(frequencies)

Analyzing Results:
insert image description here
For this analysis:

Since pygal is used for analysis rather than printing the results, it is possible to increase the number of simulated dice rolls to 1000. To analyze the results, an empty list frequencies is created to store the number of occurrences of each type of point.
.The
new loop traverses the possible points, the so-called possibility, that is, the number of 1~6 regular dice, calculates how many times each point appears in the results, and appends this value to the end of the list frequencies.

If the result is 6 values, it is reasonable, because the dice only have 6 sides, and there are only 6 possible occurrences of the result value.

Let's visualize these results below:

draw histogram

#The histogram is a bar graph that indicates the frequency of various results.
die_visual.py

from die import Die
import pygal
#创建一个D6
die = Die()

#将所投掷的几次骰子的结果存储到列表中
results =[]
for roll_num in range(1000):
    result = die.roll()
    results.append(result)

#分析结果
frequencies = []
for value in range(1,die.num_sides+1):
    frequency = results.count(value)
    frequencies.append(frequency)
#print(frequencies)

#对结果进行可视化
hist = pygal.Bar()

hist.title = "Request of rolling one D6 1000 times."
hist.x_labels = ['1','2','3','4','5','6']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D6',frequencies)
hist.render_to_file('die_visual.svg')

The previous code is still the demo of the previous summary. No changes here, just commented out the print statement. Because the histogram can be used to see the effect more intuitively, the content printed in the console is annotated.
.
Then import pygael and create an instance of pygal.Bar().
In the next setting of the title, the title of the x and y coordinates will not be mentioned. The .render_to_file method renders the drawn histogram as a file and stores it where the project file is located.

Use a browser to open the .svg file stored locally to view the effect:
insert image description here

If you encounter such problems along the way:

importError

import pygal报错ImportError: cannot import name ‘Iterable‘ from ‘collections‘

You can jump directly to the _compat.py file where the editor reports an error .

Then find the twentieth line of the line.

That is:

from collections import Iterable

Add a suffix to it and change it to:

from collections.abc import Iterable

Then save the test.

throw two dice at the same time

dice_visual.py

from die import Die
import pygal
#创建一个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)
#print(frequencies)

#对结果进行可视化
hist = pygal.Bar()

hist.title = "Request of rolling two D6 dice 1000 times."
hist.x_labels = ['2','3','4','5','6','7','8','9','10','11','12']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D6 + D6',frequencies)
hist.render_to_file('die_visual.svg')

insert image description here

Throw two dice with different sides at the same time

Let's create a 6-sided and a 10-sided die and see the results of rolling both dice 50,000 times:

from die import Die
import pygal
#创建一个D6
die_1 = Die()
die_2 = Die(10)

#将所投掷的几次骰子的结果存储到列表中
results =[]
for roll_num in range(50000):
    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)
#print(frequencies)

#对结果进行可视化
hist = pygal.Bar()

hist.title = "Request of rolling a D6 and a D10 50 dice 1000 times."
hist.x_labels = ['2','3','4','5','6','7','8','9','10','11','12','13','14','15','16']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"

hist.add('D6 + D10',frequencies)
hist.render_to_file('die_visual.svg')

View program execution results:
insert image description here

Guess you like

Origin blog.csdn.net/tianlei_/article/details/130568522