Search code examples
pythondicepython-turtle

How to draw a dice using turtle python


I'm struggling to make the dice using turtle graphics library in python but I'm stuck. Below is the image of the dice I have to make.

A demo of the dice I'm looking for

Can anybody please give me a chunk of code for the Dice? Thanks a lot


Solution

  • You could make a function like this:

    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) draws a dice from its bottom left corner with n a the number of dots. dice(0) erases the dice by drawing over it in white. [EDIT] updated code to allow dice to be drawn at any angle (based on current heading).

    Demo:

    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)