【问题标题】:How to draw a dice using turtle python如何使用龟蟒绘制骰子
【发布时间】:2021-12-06 02:00:44
【问题描述】:

我正在努力在 python 中使用 turtle 图形库制作骰子,但我被困住了。下面是我必须做的骰子的图像。

谁能给我一段骰子的代码?非常感谢

【问题讨论】:

  • 我在 link 上找到了代码,但代码有 170 多行,如果您有更短的代码想法,请帮助
  • 你经历过这个吗? codespeedy.com/…
  • @Alex 我不需要实际的游戏。我只需要用如图所示的点制作骰子。

标签: python dice python-turtle


【解决方案1】:

你可以做一个这样的函数:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 2021-03-02
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多