绘制与掷骰子次数相对应的海龟直方图

Drawing a turtle histogram that corresponds with the amount of times a dice is rolled

我对 python 还很陌生,所以请多多包涵。我正在尝试制作一个海龟直方图,用于计算各种数字出现 100 卷 3 个骰子的次数。但是在用我从掷骰子试验中得到的总数计算出直方图的最大高度后,直方图的结果与我的预期完全不同。我当前的直方图输出和预期的直方图附在下面。 #注意输出一直在变化,因为它有 randrange 在此先感谢。

当前代码

from random import randrange
import turtle

totals = dict()
for i in range(3, 19):
    totals[i] = 0
    
# TODO: Set a variable called trials here so we can loop 100 times
trials = 100
for i in range(trials):
     first_roll = randrange(1, 7)
     second_roll = randrange(1, 7)
     third_roll = randrange(1, 7)
     total = first_roll + second_roll + third_roll
     print(total)
     totals[total] += 1


maxheight = 0
for i in range(3, 19):
    print(i, totals[i])
    if totals[i] > maxheight:
        maxheight = totals[i]
scr = turtle.Screen()
t = turtle.Turtle()

t.penup()
t.goto(-138, -175)
t.pendown()

for i in range(3, 19):
    t.write(i, align="center")
    t.forward(20)

t.penup()
t.goto(-150, -175)
t.pendown()

for i in range(3, 19):
    height = int(totals[i] * 300 / maxheight)
    t.forward(height)
    t.right(90)
    t.forward(20)
    t.backward(height)
# TODO: In the end, draw the line at the bottom of our histogram

scr.exitonclick()

当前输出

预期输出

你的问题是这段代码:

for i in range(3, 19):
    height = int(totals[i] * 300 / maxheight)
    t.forward(height)
    t.right(90)
    t.forward(20)
    t.backward(height)

它没有考虑乌龟的当前方向,也没有让乌龟处于合理的方向。考虑一下:

for i in range(3, 19):
    height = int(totals[i] * 300 / maxheight)

    turtle.left(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(20)
    turtle.right(90)
    turtle.forward(height)
    turtle.left(90)

假设海龟在开始时面向 0 度,离开海龟时面向 0 度。完成代码并进行其他调整:

from random import randrange
from turtle import Screen, Turtle

TRIALS = 100
COLUMN_WIDTH = 20

totals = dict()

for i in range(3, 19):
    totals[i] = 0

for _ in range(TRIALS):
    first_roll = randrange(1, 7)
    second_roll = randrange(1, 7)
    third_roll = randrange(1, 7)
    total = first_roll + second_roll + third_roll
    totals[total] += 1

maxheight = 0

for i in range(3, 19):
    if totals[i] > maxheight:
        maxheight = totals[i]

screen = Screen()
turtle = Turtle()

turtle.penup()
turtle.goto(-160 - COLUMN_WIDTH/2, -175)
turtle.pendown()

turtle.forward(COLUMN_WIDTH)

for i in range(3, 19):
    turtle.write(i, align="center")
    turtle.forward(COLUMN_WIDTH)

turtle.penup()
turtle.goto(-160, -175)
turtle.pendown()

for i in range(3, 19):
    height = int(totals[i] * 300 / maxheight)

    turtle.left(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(COLUMN_WIDTH)
    turtle.right(90)
    turtle.forward(height)
    turtle.left(90)

turtle.hideturtle()
screen.exitonclick()