如何使用乌龟画骰子 python
How to draw a dice using turtle python
我正在努力使用 python 中的 turtle 图形库来制作骰子,但我被卡住了。下面是我必须制作的骰子的图像。
任何人都可以给我一段 Dice 的代码吗?非常感谢
你可以创建这样的函数:
import turtle as tg
def dice(face,side=100,color='blue',width=2):
tg.color(color if face else 'white')
tg.width(width)
tg.pendown()
for _ in range(4):
tg.forward(side)
tg.left(90)
faces = { 0: [(1,1),(1,3),(1,5),(3,3),(5,1),(5,3),(5,5)],
1: [(3,3)],
2: [(1,1),(5,5)],
3: [(1,1),(3,3),(5,5)],
4: [(1,1),(1,5),(5,1),(5,5)],
5: [(1,1),(1,5),(3,3),(5,1),(5,5)],
6: [(1,1),(1,3),(1,5),(5,1),(5,3),(5,5)] }
x,y = tg.pos()
offset = side/15
dotSize = (side-2*offset)/7
tg.penup()
px,py = 0,0
for dx,dy in faces[face]:
rx,ry = dx*dotSize+dotSize/2+offset,dy*dotSize+dotSize/2+offset
tg.forward(rx-px)
tg.left(90)
tg.forward(ry-py)
tg.right(90)
px,py = rx,ry
tg.dot(dotSize*1.5,color if face else 'white')
tg.goto(x,y)
dice(n)
从左下角抽取一个骰子,点数为 n
。 dice(0)
通过在其上绘制白色来擦除骰子。 [编辑] 更新代码以允许以任何角度绘制骰子(基于当前航向)。
演示:
tg.left(12) # dice angle
tg.speed(0)
tg.penup()
tg.backward(175)
dice(6)
tg.forward(125)
dice(5)
tg.forward(125)
dice(4)
tg.backward(250)
tg.right(90)
tg.forward(125)
tg.left(90)
dice(3)
tg.forward(125)
dice(2)
tg.forward(125)
dice(1)
我正在努力使用 python 中的 turtle 图形库来制作骰子,但我被卡住了。下面是我必须制作的骰子的图像。
任何人都可以给我一段 Dice 的代码吗?非常感谢
你可以创建这样的函数:
import turtle as tg
def dice(face,side=100,color='blue',width=2):
tg.color(color if face else 'white')
tg.width(width)
tg.pendown()
for _ in range(4):
tg.forward(side)
tg.left(90)
faces = { 0: [(1,1),(1,3),(1,5),(3,3),(5,1),(5,3),(5,5)],
1: [(3,3)],
2: [(1,1),(5,5)],
3: [(1,1),(3,3),(5,5)],
4: [(1,1),(1,5),(5,1),(5,5)],
5: [(1,1),(1,5),(3,3),(5,1),(5,5)],
6: [(1,1),(1,3),(1,5),(5,1),(5,3),(5,5)] }
x,y = tg.pos()
offset = side/15
dotSize = (side-2*offset)/7
tg.penup()
px,py = 0,0
for dx,dy in faces[face]:
rx,ry = dx*dotSize+dotSize/2+offset,dy*dotSize+dotSize/2+offset
tg.forward(rx-px)
tg.left(90)
tg.forward(ry-py)
tg.right(90)
px,py = rx,ry
tg.dot(dotSize*1.5,color if face else 'white')
tg.goto(x,y)
dice(n)
从左下角抽取一个骰子,点数为 n
。 dice(0)
通过在其上绘制白色来擦除骰子。 [编辑] 更新代码以允许以任何角度绘制骰子(基于当前航向)。
演示:
tg.left(12) # dice angle
tg.speed(0)
tg.penup()
tg.backward(175)
dice(6)
tg.forward(125)
dice(5)
tg.forward(125)
dice(4)
tg.backward(250)
tg.right(90)
tg.forward(125)
tg.left(90)
dice(3)
tg.forward(125)
dice(2)
tg.forward(125)
dice(1)