Example #1
1
import turtle
t = turtle.Pen()
number = int(turtle.numinput("변 또는 동그라미의 수",
             "변 또는 동그라미의 수를 입력해 주세요:",6))
shape = turtle.textinput("어떤 모양을 원하십니까?",
                         "p는 세모,r는 동그라미:")
for x in range(number):
    if shape == 'r':
        t.circle(100)
    else:
        t.forward(150)
    t.left(360/number)

def ask_speed_and_angle():
    #speed_default = Data.speed # data["speed"]
    #try:
    #new_speed = float(input(f"inital speed in [m/s] (enter={speed_default})"))
    lines = "\n".join(Data.history)
    new_speed = turtle.numinput(
        title="please enter speed: (0 to quit)",
        prompt=f"{lines}\n\nspeed in [m/s] >>>",
        default=Data.speed,
    )
    #except ValueError:
    #    new_speed = speed_default
    #print("speed is set to", new_speed)
    Data.speed = new_speed  #data["speed"] = new_speed

    #angle_default = Data.angle # data["angle"]
    #try:
    #new_angle = float(input(f"angle in degree (enter={angle_default})"))
    new_angle = turtle.numinput(
        title="please enter angle: (0 to quit)",
        prompt=f"{lines}\n\nangle in [Grad] >>>",
        default=Data.angle,
    )
    #except ValueError:
    #    new_angle = angle_default
    #print("angle is set to", new_angle)
    Data.angle = new_angle  #data["angle"] = new_angle
Example #3
0
def shapes(wid, hi):
    width = turtle.numinput(" ", "Enter a width: ")
    height = turtle.numinput(" ", "Enter a height: ")
    hypotenuse = math.hypot(width, height)  #triangle, hypotenuse math function
    print("Hypotenuse length of Right Triangle: ", hypotenuse)
    angle1 = (90 - (math.degrees(math.atan(width / height))))
    angle2 = (180 - (90 - angle1))
    turtle.speed(1)
    turtle.showturtle()
    turtle.left(90)
    turtle.forward(height)  #height
    turtle.right(90)
    turtle.forward(width)  #width
    turtle.right(90)
    turtle.forward(height)  #height
    turtle.goto(0, 0)  #back to origin
    turtle.left(90)
    turtle.forward(width)  #width
    turtle.forward(width)  #width
    turtle.left(angle1)
    turtle.forward(hypotenuse)  #hypotenuse
    turtle.right(angle2)
    turtle.forward(height)  #height
    turtle.right(90)
    turtle.forward(width)  #width
    turtle.goto(0, 0)  #back to origin
Example #4
0
def main():
    def tick(x, y):
        cellsProbed, bombLeft = gameBoard.probe(x, y)
        if (bombLeft == numBombs and cellsProbed == (
            (boardSize**2) - numBombs)) or bombLeft < numBombs:
            c = turtle.textinput("Number of tries: {}".format(cellsProbed),\
                              "Play again? (y)es or (n)o?: ")
            if c == "y":
                main()
            elif c == "n":
                turtle.bye()

    boardSize = int(turtle.numinput("Minesweeper",
                                    "Board Size? (size x size)"))
    totCells = boardSize * boardSize
    gameBoard = game.Game(boardSize)

    done = False
    while not done:
        numBombs = int(turtle.numinput("Minesweeper",\
                                   "How many bombs do you want to hide?"))
        done = gameBoard.hideMines(numBombs)

    turtle.onscreenclick(tick)
    turtle.mainloop(
    )  #  Pycharm closes automatically, need this to keep it open.
Example #5
0
def chooseSettings():
    #Get user input to determine to settings.
    global mapwidth, tilesize, generator
    #Ask the user which generator they want to use.
    gen = turtle.numinput('DigiMapGen',
                          'Input a generator number:',
                          1,
                          minval=0,
                          maxval=gencount)
    #Make sure the user put in a real generator.
    if gen in range(gencount + 1): generator = gen
    else:
        logger.warn('ERROR: Invalid generator.')
        chooseSettings()
    #Ask the user how many tiles across they want the map to be.
    mapwidth = int(turtle.numinput('DigiMapGen', 'Set map width:', 50))
    #Get animation delay from user.
    delay = turtle.numinput('DigiMapGen', 'Set animation delay:', 0)
    if delay <= 0:
        turtle.tracer(False)
        turtle.delay(delay)
        turtle.speed(0)
    else:
        turtle.delay(delay)
    #Get the window size from the config.
    if conf.windowsize / 100 > 1: winsize = 1
    else: winsize = conf.windowsize / 100
    getMonitorDimensions()
    turtle.setup(monitorheight * winsize, monitorheight * winsize)
    newTileSize(mapwidth)
def get_grocery_list(save, user='', user_pass={}, user_order={}):
    dct = dict()
    foods = food_dict()
    string = ''
    while True:
        item = t.textinput("Grocery List", string + "Enter item name, or enter 'stop' when all items entered:")
        string = ''
        item = item.upper()
        if item == 'STOP':
            main(dct)
            t.reset()
            t.setworldcoordinates(0, 0, 100, 100)
            t.goto(50, 50)
            t.write("Prices Printed", align='center', font=("Arial", 32, "normal"))
            t.goto(-100, -100)
            if save:
                if check_yes(t.textinput("Save Order", "Would you like to save this order to quick order?")):
                    dct = dict_format(dct)
                    user_order[user] = dct
                    save_order(user, user_pass, user_order)
            return
        if item in foods:
            if foods[item] == 'LB':
                quantity = t.numinput("Quantity", "Enter the amount in lbs you would like:", 1, 0, 100000000000000)
                dct[item] = quantity
            elif foods[item] == 'OZ':
                quantity = t.numinput("Quantity", "Enter the amount in oz you would like:", 1, 0, 100000000000000)
                dct[item] = quantity
            else:
                quantity = t.numinput("Quantity", "Enter the quantity  you would like:", 1, 0, 100000000000000)
                dct[item] = quantity
        else:
            string = "Item not found. "
Example #7
0
def draw_pos(x, y):
    t.clear()
    t.penup()
    t.goto(0, 0)
    r = int(t.numinput("insert", "radius:"))
    angle = int(t.numinput("insert", "angle:"))
    a = (180 - angle) / 2
    s = 2 * r * math.cos(math.radians(a))
    t.speed(0)
    t.penup()
    t.goto(0, -r)
    t.pendown()
    t.circle(r)
    t.penup()
    t.goto(0, 0)
    for rotate in range(120):
        t.penup()
        t.forward(r)
        t.left(180 - a)
        t.pendown()
        t.forward(s)
        t.left(180 - a)
        t.penup()
        t.forward(r)
        t.left(180 - angle)
        t.right(5)
Example #8
0
def draw_track(x, y):
    velocity = t.numinput("입력", "속도 :", 50, 30, 100)
    ##turtle.numinput():두개의 인자를 요청하는 함수이며, 첫 인자는 'prompt'두 번째 인자는'default'입니다.
    ##prompt는 입력하려고 하는 숫자를 설명하는 내용의 텍스트 'default'는 값을 입력하지 않았을 때 함수가 받아들일 값입니다.

    angle = math.radians(t.numinput("입력", "각도", 30, 0, 360))
    ## 도>라디안으로 바꿔주는 함수입니다. ex)radians(90)=1.57

    t.clearstamps()  ## 화면의 모든 스탬프를 클리어합니다.
    t.hideturtle()  ##거북이를 화면에서 숨기는 기능의 함수입니다. showturtle와 반대의 함수
    t.setpos(x, y)  ## 좌표(x,y)로 이동 == t.goto(a,b)와 같은 함수
    t.showturtle()  ##거북이를 화면에 표시하는 함수
    t.stamp()  ##현재위치에 스탬프 찍기

    hl = -(t.window_height() / 2)
    # t.window_height() : 터틀창의 높이를 반환하는 함수

    ux = velocity * math.cos(angle)
    uy = velocity * math.sin(angle)

    while True:
        uy = uy + (-1 * a_g) * drawing_time
        dy = t.ycor() + (uy * drawing_time) - (a_g * drawing_time ** 2) / 2
        ##t.ycor() : 현재위치의 y좌표 반환
        dx = t.xcor() + (ux * drawing_time)
        # t.xcor() : 현재위치의 x좌표 반환

        if dy > hl:
            t.goto(dx, dy)
            t.stamp()
        else:
            break  ##완료시 반복문 탈출
Example #9
0
def main():
    turtle.hideturtle()
    turtle.shape('turtle')
    turtle.speed(0)

    # Meminta input untuk rows, pixels, dan petals.
    rows = int(
        turtle.numinput("Colorful Chessboard and Flower",
                        "Enter the number of rows: ", None, 2, 25))

    pixels = turtle.numinput("Colorful Chessboard and Flower",
                             "Enter the square size (pixels): ", None, 1,
                             int(300 / rows))

    petals = int(
        turtle.numinput("Colorful Chessboard and Flower",
                        "Enter the number of petals of the flower: ", None, 2,
                        360))

    side_Length = rows * pixels  # Menghitung panjang sisi.

    # Memanggil fungsi menggambar Flower dan Chessboard.
    # Dan menulis Sentence.
    draw_Flower(petals, side_Length)
    draw_Chessboard(rows, pixels)
    print_Sentence(rows, petals, side_Length)

    turtle.exitonclick()
Example #10
0
def draw_pos(x, y):
    velo = t.numinput("입력 : ", "속도 : ", 50, 10, 100)
    ang = math.radians(t.numinput("입력 : ", "각도 : ", 45, 0, 360))

    t.clear()
    t.hideturtle()
    t.setpos(x, y)
    t.showturtle()
    t.stamp()

    hl = -(t.window_height()/2)

    ux = velo * math.cos(ang)
    uy = velo * math.sin(ang)

    while True:
        uy = uy + (-1 * 9.8) * tm
        dy = t.ycor() + (uy * tm) - (g*tm**2)/2
        dx = t.xcor() + (ux * tm)

        if dy > hl:
            t.goto(dx, dy)
            t.stamp()
        else:
            break
Example #11
0
def main():
    turtle.speed(0)
    t = 0
    length = int(turtle.numinput("", "Enter the length of each side: "))
    times = int(
        turtle.numinput("",
                        "Enter the numbr of the squares you want to draw: "))
    while t <= times:
        drawsquare(length)
        turtle.left(360 / times)
        t += 1
Example #12
0
def main_program():
    turtle.bgcolor("black")
    k = turtle.numinput("Vanishing Point X-coordinate", "Input the x-coordinate for t"
                                                        "he vanishing point and press ENTER.", -5)
    b = turtle.numinput("Vanishing Point Y-coordinate", "Input the y-coordinate for t"
                                                        "he vanishing point and press ENTER.", 5)
    turtle.hideturtle()
    turtle.clearscreen()
    turtle.bgcolor("black")
    draw(-10, 0, 0, k, b)  # Starting point.
    draw(12, 5, 6, k, b)
    main_program()
    turtle.mainloop()
Example #13
0
def figura():
    lados = turtle.numinput("Lados", "Ingrese cuantos lados tendra la figura:")
    tamaño = turtle.numinput("Tamaño", "Ingrese el tamaño de la figura:")
    relleno = turtle.textinput("relleno", "Desea rellenar la figura")
    pipo.clear()
    pipo.color("#1AB231", "#19EC38")
    pipo.begin_fill()
    pipo.pensize(5)
    for i in range(int(lados)):
        pipo.forward(tamaño)
        pipo.right(-360 / lados)
        turtle.color("black", "red")
    if relleno == "si":
        pipo.end_fill()
Example #14
0
def throwDice(player, m):
	if (SIMULATION):
		d1 = random.randint(1,6)
		d2 = random.randint(1,6)
	else:
		d1 = int(turtle.numinput(m[7] + Player, m[17], minval=1, maxval=6))
		d2 = int(turtle.numinput(m[7] + Player, m[18], minval=1, maxval=6))

	if d1 == d2:
		score = -(d1+d2)
		message (m[7] %(player, str(d1), str(score)))
	else:
		score = d1+d2
		message (m[8] %(player, str(d1), str(d2), str(score)))
	return score
Example #15
0
def main():
    m = int(input("Please input the length of the wall:"))
    n = int(input("Please input the width of the wall:"))
    a = int(input("Please input the length of the brick:"))
    b = int(input("Please input the width of the brick:"))
    #输入部分结束
    for i in range(m * n):
        li.append(0)
    #初始化列表结束
    arrange(m, n, a, b, li, 0)
    #安排结束
    Fin = []
    for i in Alist:
        Fin.append(c.deepcopy(tuple(convert(m, a, b, i))))
    #转化为要求形式结束
    num = 0
    Final = []
    Final = list(set(Fin))
    #除重结束
    if len(Final) == 0:
        print(False)
    #若无返回值则认为不能铺
    else:
        for i in Final:
            num = num + 1
            print(num, ' ' * (10 - len(str(num))), list(i))
        x = t.numinput('Select one type.',
                       'Please select which one you would like to print:',
                       default=None,
                       minval=1,
                       maxval=len(Final) + 1)
        draw(a, b, Alist[int(x - 1)])
Example #16
0
def tt_game():
    num = randint(1, 100)
    t = 1
    inputn = numinput('Guess a number', 'Guess a number that between 1 and 100:')
    while True:
        if num == inputn:
            o = '''%s was the number! You win! You just try %s time! Please press [cancel] or input '0' to exit.''' % (round(num), t)
            numinput('Guess right', o)
            done()
            break
        elif num < inputn:
            inputn = numinput('Guess again', 'Guess lower!')
            t += 1
        elif num > inputn:
            inputn = numinput('Guess again', 'Guess higher!') 
            t += 1
def enterMoveVsCPU():
    '''Asks the player for the grid position they want to make their move
       Checks to see if it is a valid move (grid square hasn't already been chosen)
       This function also updates the grid, similar to makeMove() for the multiplayer version
       From this it either calls cpuMakeMove(), or ends the game if the move completed the game'''

    try:
        # Ask for input using a messagebox
        gridPosition = int(turtle.numinput("Player's turn", "Enter your move:", minval = 1, maxval = 9))

        # If the user clicks 'Cancel' it raises a type error, but for the game this means they want to save the game
        # and return to it later
    except TypeError:
        saveGame()

    # Check that this move is valid, and hasn't already been made
    if (gridSquares[gridPosition] == 1) or (gridSquares[gridPosition] == 2):
        messagebox.showinfo("Invalid Move", "This grid square has already been used. Please select another")
        enterMoveVsCPU()

    gridSquares[gridPosition] = 1

    drawCross(gridPosition)
        
    status = checkGameStatus(gridSquares)

    if(status=="Crosses Wins") or (status=="Noughts Wins") or (status=="Game Drawn"):
        endGame(status)
    else:
        cpuMakeMove()
Example #18
0
 def modificarBombas(self):
     return int(
         turtle.numinput("Menu",
                         prompt="Ingrese una cantidad de bombas (1-" +
                         str(self.__maxbombas) + ")",
                         minval=1,
                         maxval=self.__maxbombas))
Example #19
0
def main():
    """main module
    """
    m = int(input("Please enter the length of the wall:"))
    n = int(input("Please enter the width of the wall:"))
    a = int(input("Please enter the length of the tile:"))
    b = int(input("Please enter the width of the tile:"))
    visited = [0] * (m * n)
    alls = tile(m, n, a, b, visited)
    num = len(alls)
    print("There are", num, "ways to pave this wall.")
    for i in alls:
        print(i)
    if num != 0:
        choice = turtle.numinput(
            "Visualization",
            "Enter the sequence number of the paving method you want to display: (0 - "
            + str(num - 1) + ")",
            0,
            minval=0,
            maxval=num - 1)
        subject = alls[int(choice)]
        visualization(m, n, subject)
    else:
        print("No solution can be visualized.")
Example #20
0
def output(n, m, a0, a1):
    '''画图函数
    '''
    a = int(t.numinput('输入', "括号内为起始点、终止点坐标,请输入你的选择"))
    y = t.Turtle()
    y.speed(0)
    y.hideturtle()
    y.penup()
    y.goto(-40, 0)
    y.write('纵坐标')
    y.goto(-30, -20)
    y.write('横坐标')
    for i in range(n + 1):
        y.goto(i * 30 + 15, -20)
        y.write(i + 1, False, align='center', font=("Arial", 10, "normal"))
    for i in range(m + 1):
        y.goto(-20, i * 30 + 15)
        y.write(i + 1, False, align='center', font=("Arial", 10, "normal"))
    #画坐标
    for i in range(n + 1):
        for j in range(m + 1):
            write(i, j, i + 1, j + 1, y)
    #画背景方块
    y.pensize(5)
    y.color('blue')
    for i in range(len(so1[a - 1])):
        if (so3[a - 1][i] == 1):  #如果是横着的方块,则横着画
            write(so1[a - 1][i], so2[a - 1][i], so1[a - 1][i] + a0,
                  so2[a - 1][i] + a1, y)
        else:  #竖着的方块就竖着画
            write(so1[a - 1][i], so2[a - 1][i], so1[a - 1][i] + a1,
                  so2[a - 1][i] + a0, y)
    #time.sleep(5)
    t.done()
Example #21
0
def main():
    recurse(solve)
    if solves == []:
        print('No solution, please try other values')
        input()
    else:
        print("Found %i solution(s)." % len(solves))
        print(
            'I recommend not to print the solutions if the number is large,' +
            'For printing all of them can be really slow.')
        print('You can still view the visualization of any of the solutions.')
        doprint = input('Input Y to print the solutions...')
        if doprint == "Y":
            answer = formatres(solves)
            for ans in answer:
                print(ans)
        else:
            pass
        maxi = (len(solves)) - 1
        tm = int(
            turtle.numinput("salty fish",
                            "Input number of 0 - %i:" % maxi,
                            0,
                            minval=0,
                            maxval=maxi))
        visualize(solves[tm])
        input()
Example #22
0
def main():
    """
    The function runs the calculation part of tile.py to output the possible
    combination of complete tiling patterns from user's dimension inputs, then 
    prompt the user to select a method of tiling and display it graphically.
    """

    m = int(input("length of wall:"))
    n = int(input("width of wall:"))
    a = int(input("length of tile:"))
    b = int(input("width of tile:"))

    if m * n % a * b != 0:
        error1 = "Wall cannot be covered completely by given tile dimension." + "\n" + "Unable to perform calculation."
        print(error1)
        return error1
    elif m == n == a == b:
        error2 = "The tile is the size of the wall. No need for any calculations."
        print(error2)
        return error2
    else:
        matrix = [0] * (m * n)
        wall_identity = wall(m, n)
        final = tile_combi(m, n, a, b, wall_identity, matrix, [], [])
        num = len(final)
        for p in range(num):
            print(final[p], "\n")
        print("Total number of possible combination:{0}".format(num))
        max_num = num - 1
        choice = int(
            turtle.numinput("How to tile the wall?",
                            "Select a tiling method from 0 - " + str(max_num),
                            None, 0, max_num))
        method = final[choice]
        wall_draw(m, n, method, wall_identity)
Example #23
0
def main():
    sidelength = turtle.numinput("Welcome to turtle world!",
                                 "please enter the length you want")
    turtle.left(36)
    turtle.fd(sidelength)
    for i in range(0, 4):
        turtle.left(144)
        turtle.fd(sidelength)
Example #24
0
def change_number():
    global num_of_slices, num_of_rect
    num_of_slices = int(turtle.numinput("Pizza", "Number of slices:",
                                        minval=1))
    if num_of_rect > num_of_slices:
        num_of_rect = num_of_slices
    turtle.listen()
    draw()
Example #25
0
def turtlestar():

    length = turtle.numinput("Inbox", "Enter desired length: ")

    turtle.left(36)
    for i in range(5):
        turtle.forward(length)
        turtle.left(144)
Example #26
0
def drawing(step):
    import turtle
    wn = turtle.Screen() 
    
    #定义画笔,选择其中一种方案
    t = turtle.Pen()
    t.penup()
    t.speed(0)
    step = 0
    
    n = int(turtle.numinput('选择一种要画的方案','最小值=0,最大值='+str(len(answers)-1),\
                            default=None,minval=0,maxval=len(answers)-1))
    
    #计算格子位置,画出方格并标号
    l1 = -(d+1)//2
    l2 = -d//2+20*d+1
    r1 = -(c+1)//2
    r2 = -c//2+20*c+1
    for y in range(l1,l2,20):
        for x in range(r1,r2,20):
            if step < 10:
                t.goto(x+8,y+2)
                t.write(step)
            else:
                t.goto(x+5,y+2)
                t.write(step)
            #在格子合适位置处标数字
            t.goto(x,y)
            t.pendown()
            t.forward(20)
            t.left(90)
            t.forward(20)
            t.left(90)
            t.forward(20)
            t.left(90)
            t.forward(20)
            t.left(90)
            t.penup()
            step = step +1
                
    yourchioce = eval(answers[n]) 
    colors = ["bisque","goldenrod","lightseagreen","firebrick","peru","chocolate"]
    k = 0
    for i in yourchioce:
        #遍历所选方案中的砖块位置
        for j in i:
            #将同一块砖涂上同样的颜色
            if j == step:
                t.color(colors[k])
                t.begin_fill()
                drawing(j)
                t.end_fill()
            if k > 6:
                k = 0
            else:
                k = k+1
Example #27
0
 def __init__(self):
     self.dice = []
     self.current_side = None
     dice_sides = turtle.numinput(
         "Dice number",
         "How many sides for your dice? (min 1, max 12)",
         maxval=12,
         minval=1)
     for i in range(int(dice_sides)):
         self.dice.append(i + 1)
Example #28
0
def poligono_regolare():

    # inizializzo turtle
    artista = turtle.Turtle()  # Inizializzo la nostra tartaruga
    artista.color("red")
    #tento di ricevere dei dati ed elaborarli per formare una figura
    try:
        N = int(
            turtle.numinput(
                "Domanda",
                "Inserisci il numero dei lati di un poligono (compreso tra 3 e 12, 11 escluso):"
            ))
        L = int(turtle.numinput("Domanda", "Inserisci la misura del lato:"))

    except ValueError:
        print("Ehi! Devi inserire un numero intero...")
        N = int(
            turtle.numinput(
                "Domanda",
                "Inserisci il numero dei lati di un poligono (compreso tra 3 e 12, 11 escluso):"
            ))
        L = int(turtle.numinput("Domanda", "Inserisci la misura del lato:"))
    numero = {
        3: 0.289,
        4: 0.5,
        5: 0.688,
        6: 0.866,
        7: 1.038,
        8: 1.207,
        9: 1.374,
        10: 1.539,
        12: 1.866
    }  # Creo un dizionario dove inserisco i numeri fissi
    numero_fisso = numero[N]
    apotema = (numero_fisso * L)
    perimetro = (N * L)
    area = (perimetro * apotema / 2)

    text.insert(END, area)
    per.insert(END, perimetro)
    for i in range(N):
        artista.fd(L)
        artista.lt(360 / N)
Example #29
0
def circonferenza():
    # inizializzo turtle
    artista = turtle.Turtle()
    artista.color("red")
    try:
        r = int(turtle.numinput("Raggio", "Inserisci il raggio del cerchio:"))
        g = int(turtle.numinput("Gradi", "Inserisci i gradi del cerchio:"))
    except ValueError:
        print("Ehi! Devi inserire un numero intero...")
        r = int(turtle.numinput("Raggio", "Inserisci il raggio del cerchio:"))
        g = int(turtle.numinput("Gradi", "Inserisci i gradi del cerchio:"))

    artista.circle(r, g)
    area = r**2 * math.pi
    circon = (math.pi * 2) * r
    #inserisco i valori nelle textbox
    text.insert(END, area)
    per.insert(END, circon)
    turtle.mainloop()
Example #30
0
def sp2(): #彩色螺旋图形2
    colors = ["red", "gray","yellow","blue","purple","green","orange","white","yellow"]
    sides = int(turtle.numinput('Title','How many circles do you want(1 - 8)?',4,1,8)) #范围在1到8,默认4
    '''
    sides -- How many sides does the spiral have
    '''
    for x in range(180):
        t.pencolor(colors[x % sides]) #选择颜色
        t.circle(x) #画圆
        t.left(360 / sides + 2)
        t.width(x * sides / 175) #修改笔的粗细,增加宽度或厚度
    turtle.done()
Example #31
0
def draw_pos(x,y):
    v = t.numinput("입력","속력:",50,10,100)
    angle = math.radians(t.numinput("입력","각도:",45,0,360))
    t.hideturtle()
    t.goto(-200, 150)
    t.clearstamps()
    t.hideturtle()
    t.showturtle()
    t.stamp()
    hl = -(t.window_height() / 2)
    ux = v * math.cos(angle)
    uy = v * math.sin(angle)
    while True:
        uy = uy + (-1*g)*tm
        dy = t.ycor() + uy - (g*tm)
        dx = t.xcor() + (ux*tm)
        if dy > hl:
            t.goto(dx,dy)
            t.stamp()
        else:
            break;
Example #32
0
def sp3(): #彩色螺旋图形3
    colors = ['red','blue','purple','pink','orange','yellow']
    sides = int(turtle.numinput('Title','How many sides do you want(2 - 6)?',5,2,6)) #范围在2到6,默认5
    '''
    sides -- How many sides does the spiral have
    '''
    for x in range(360):
        t.pencolor(colors[x % sides]) #选择颜色
        t.forward(x * 3 / sides + x)
        t.left(360 / sides + 1)
        t.width(x * sides / 200) #修改笔的粗细,增加宽度或厚度
    turtle.done()
def enterMove(playerTurn):
    '''Asks the player for the grid position they want to make their move
       Checks to see if it is a valid move (grid square hasn't already been chosen)
       Increments a counter to see whose turn it is, depending on this number being 
       even or odd decides the turn so that the right symbol/value is used
       Uses this input to call function makeMove() with inputs gridPosition and playerTurn'''

    # Information for displaying the correct symbol in the input pop-up box
    if playerTurn % 2 ==0:
        symbol = "X"

    else:
        symbol = "0"

    try:
        # Ask for input using a messagebox
        gridPosition = int(turtle.numinput("Player " +  symbol + "'s turn", "Enter your move:", minval = 1, maxval = 9))

        # If the user clicks 'Cancel' it raises a type error, but for the game this means they want to save the game
        # and return to it later
    except TypeError:
        saveGame() 
        
    # Check that this move is valid, and hasn't already been made
    if (gridSquares[gridPosition] == 1) or (gridSquares[gridPosition] == 2):
        messagebox.showinfo("Invalid Move", "This grid square has already been used. Please select another")
        enterMove(playerTurn)

    # Counter to increase player turn every time enterMove is called, and is a valid move
    playerTurn = playerTurn + 1

    # Work out whose turn it is based on the counter of how many turns there have been
    # An even number turn means it is noughts turn, an odd turn number means it is crosses turn
    if playerTurn % 2 == 0:
        playerTurn = 2
        
    else:
        playerTurn = 1

    makeMove(gridPosition, playerTurn)
# RosettesAndPolygons.py - a spiral of polygons AND rosettes!
import turtle
t = turtle.Pen()
t.speed(0)
# Ask the user for the number of sides, default to 4
sides = int(turtle.numinput("Number of sides",
            "How many sides in your spiral?", 4))
# Our outer spiral loop for polygons and rosettes, from size 5 to 75
for m in range(5,75):   
    t.left(360/sides + 5)
    t.width(m//25+1)
    t.penup()        # Don't draw lines on spiral
    t.forward(m*4)   # Move to next corner
    t.pendown()      # Get ready to draw
    # Draw a little rosette at each EVEN corner of the spiral
    if (m % 2 == 0):
        for n in range(sides):
            t.circle(m/3)
            t.right(360/sides)
    # OR, draw a little polygon at each ODD corner of the spiral
    else:
        for n in range(sides):
            t.forward(m)
            t.right(360/sides)

   


Example #35
0

# from tkinter import SimpleDialog
# SimpleDialog.textinput()



answer = turtle.textinput("Играть?", "y/n")

if answer == 'n':
    sys.exit()

try_count = 0

while True:
    number = turtle.numinput("Угадайте", "Число", 0, 0, 100)

    if number == x:
        turtle.color('green')
        gotoxy(-150, 200)
        turtle.write("Ура! Вы победили!", 
                font=("Arial", 28, "normal"))
        break

    else:
        turtle.color('red')
        gotoxy(-150, 100)
        turtle.write("Неверно!",
            font=("Arial", 28, "normal")) 

        try_count += 1
 
 redrawCard(dealerCoords,dealerHand)
 
 # creates deck image
 turtle.register_shape(imagePath + 'deck.gif')
 playerHand = turtle.Turtle(imagePath + 'deck.gif', visible=False)
 playerHand.pu()    
 playerHand.setposition(-150,0)
 playerHand.showturtle()
 
 if playerScore < 21 and dealerScore < 21:
     # used for dealing new cards
     playerHit = True
     dealerHit = False
     
     bet = (turtle.numinput('Bet','Enter your bet? ($1-$'+str(playerMoney)+')'
     ,minval=1, maxval=playerMoney))
     
     while playerHit:
         hit = (turtle.textinput('Hit','Hit or stay (h/s)?'))
         hit = hit.lower()
         
         if hit == 'h' and playerScore < 21:
             # adds a card to the hand and calculates score
             a.addCard(p.hand)
             playerScore = getScore(p.hand,playerScore)
             
             for i in p.hand:
                 if i[0] == 'A' and playerScore >= 21:
                     playerScore -= 10
             
             # creates new card
# ColorMeSpiralled.py 

import turtle   # set up turtle graphics
t=turtle.Pen()
t.speed(0)
turtle.bgcolor('black')
# Set up a list of any 10 valid Python color names
colors=['red', 'yellow', 'blue', 'green', 'orange',
        'purple', 'white', 'gray', 'brown', 'sea green']

# ask the user's name using turtle's textinput popup window
your_name = turtle.textinput("Enter your name", "What is your name?")

# ask the number of sides
sides = int(turtle.numinput("Number of sides",
                            "How many sides do you want (1-10)?", 5, 1, 10))

# draw a spiral of the name on the screen, written 100 times
for x in range(100):
    t.pencolor(colors[x%sides%10]) # rotate through the 10 colors
    t.penup()       # don't draw the regular spiral lines
    t.forward(x*4)  # just move the turtle on the screen
    t.pendown()     # now, write the user's name, bigger each time
    t.write(your_name, font=("Times", int( (x*2 + 4) / 4), "bold") )
    t.left(360/sides+2)      # turn left 360/sides+2 degrees for sides

Example #38
0
import turtle

t = turtle.Pen()
# 얼만큼 동그라미를 그릴건지 물어봄.
number_of_circles = int(turtle.numinput("동그라미의 수",
                                        "얼만큼 동그라미를 그려주기를 원함니까?",6))
for x in range(number_of_circles):
    t.circle(100)
    t.left(360 / number_of_circles)

input("")
Example #39
0
    turtle.left(90)
    turtle.forward(200)
    turtle.left(90)
    turtle.penup()
    turtle.goto((x1+50),(y1+50))        #Sends turtle to location to begin second square
    turtle.pendown()
    turtle.pencolor("Red")
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(100)
    turtle.penup()
    x=turtle.numinput("Input","Enter x coordinate")     #Gets user input
    y=turtle.numinput("Input","Enter y coordinate")     #Gets user input
    turtle.goto(x,y)                                    #Sends turtle to user inputed coordinates
    if x >= (x1+50) and x <= (x1+150) and y >= (y1+50) and y <= (y1+150):   #If turtle is in smaller square.
        score = score + 2                                                   #2 points for turtle in smaller square
        turtle.write("  You are in!  Score: %d" %score)
    elif x >= x1 and x <= (x1 + 200) and y >= y1 and y <= (y1 + 200):       #If turtle is in larger square.
        score = score + 1                                                   #1 point for turtle in larger square.
        turtle.write("  Almost there!  Score: %d" %score)
    else:                                                #Turtle not in any square
        score = score - 1                                # - 1 point if turtle not in either square.
        turtle.write("  We missed you!  Score: %d" %score)
    game = turtle.textinput("Player Input", "Would you like to continue? (Y/N)") #Asks user to continue
turtle.clear()                                          #Clears all the squares
turtle.write("  Game Over.  Your Score is %d" %score)   #Gives final score
turtle.mainloop()                                       #Keeps turtle on screen
Example #40
0
import turtle
t = turtle.Pen()
t.penup()
turtle.bgcolor("black")
sides = int(turtle.numinput("변의 수",
                            "얼만큼 변의 수를 정하시겠슴니까(2-6)?", 4, 2, 6))
colors = ["red","yellow","blue","green","orange","purple"]
for m in range(100):
    t.forward(m*4)
    position = t.position()
    heading = t.heading()
    print(position, heading)
    for n in range(int(m/2)):
        t.pendown()
        t.pencolor(colors[n%sides])
        t.forward(2*n)
        t.right(360/sides - 2)
        t.penup()
    t.setx(position[0])
    t.sety(position[1])
    t.setheading(heading)
    t.left(360/sides + 2)
input("")

Example #41
0
import turtle
t = turtle.Pen()
sides = int(turtle.numinput("변의수",
                            "얼만큼으로 변의 수를 정하시겠습니까?",4)) # 변의 수 정하기

for m in range(5,75):
    t.left(360/sides + 5)
    t.width(m//25+1)
    t.penup()
    t.forward(m*4)
    t.pendown()
    if (m % 2 == 0):
        for n in range(sides):
            t.circle(m/3)
            t.right(360/sides)

        else:
            for n in range(sides):
                t.forward(m)
                t.right(360/sides)
Example #42
0
import turtle
turtle.showturtle()
turtle.penup()
turtle.goto(0,-100)
turtle.pendown()
turtle.circle(100)
xcor=turtle.numinput("User Input","Enter x coordinate")
ycor=turtle.numinput("User Input","Enter y coordinate")
turtle.goto(xcor,ycor) 
Example #43
0
# ColorSpiralInput.py
import turtle                       # Set up turtle graphics
t = turtle.Pen()
turtle.bgcolor("black")
# Set up a list of any 8 valid Python color names
colors = ["red", "yellow", "blue", "green", "orange", "purple", "white", "gray"]
# Ask the user for the number of sides, between 1 and 8, with a default of 4
sides = int(turtle.numinput("Number of sides",
                            "How many sides do you want (1-8)?", 4, 1, 8))
# Draw a colorful spiral with the user-specified number of sides
for x in range(360):
    t.pencolor(colors[x % sides])   # Only use the right number of colors
    t.forward(x * 3 / sides + x)    # Change the size to match number of sides
    t.left(360 / sides + 1)         # Turn 360 degrees / number of sides, plus 1
    t.width(x * sides / 200)        # Make the pen larger as it goes outward

    
Example #44
0
import turtle
import math
import time



hi = []
bi = []
ai = []
area = 0

mode = turtle.numinput("選擇模式", "模式 1 為 無限模式  模式 2 為有限模式", 2, minval = 1, maxval = 2)
degree = turtle.numinput("選擇角度", "0 < 角度 <= 45", 15, minval = 10 ** -10, maxval = 45)
tri = turtle.numinput("選擇正方形邊長", "0 < 邊長", 250, minval = 10 ** -10, maxval = 10 ** 10)
turtle.speed(-1)
turtle.color('black','white')
turtle.pensize(0.5)
turtle.begin_fill()
turtle.penup()
turtle.goto(-(tri / 2),(tri / 2))
turtle.pendown()
turtle.hideturtle()

for i in range(4):
	turtle.forward(tri)
	turtle.right(90)	
turtle.end_fill()

i = 0

while True:	
# CircleSpiralInput.py - Challenge Problem
import turtle   # set up turtle graphics
t=turtle.Pen()
t.speed(0)
turtle.bgcolor('black')
# Set up a list of any 8 valid Python color names
colors=['red', 'yellow', 'blue', 'green',
        'orange', 'purple', 'white', 'gray']
# Ask the user for the number of sides, between 1 and 8, default of 4
sides = int(turtle.numinput("Number of circles",
your_name = turtle.textinput("Enter your name", "What is your name?")                            "How many circles do you want (1-8)?", 4, 1, 8))
# Draw a colorful spiral with the user-specified number of circles
for x in range(180):
    t.pencolor(colors[x % sides])   # only use the right number of colors
    t.circle(x)                     
    t.left(360 / sides + 1)         # turn 360 degrees / # of sides, plus 1
    t.width(x * sides / 200)        # make the pen larger as it goes outward
    
Example #46
0
import turtle, random
t=turtle.Pen()
turtle.bgcolor("black")
colors = ["red", "green", "blue", "pink", "purple", "yellow"]

storona = int(turtle.numinput("Количество сторон", "Сколько сторон у Вашего многоугольника?",4, 3, 360))
povtor = int(turtle.numinput("Количество повторений", "Сколько раз нарисовать многоугольники?",4, 1, 360))
for x in range(povtor):
    t.pencolor(random.choice(colors))
    for i in range(storona):
        t.forward(100)
        t.left(360/storona)
    t.left(360/povtor)
Example #47
0
import turtle, random

colors = ["red", "orange", "white", "green", "blue", "pink", "purple", "yellow"]
storona = 20


t = turtle.Pen()
t.width(3)
turtle.speed(150)
turtle.bgcolor("black")
square = int(turtle.numinput("Количество квадратов", "Сколько квадратов нарисовать?",4, 1, 360))
for i in range(square):
    rnd_color = random.choice(colors)
    t.pencolor(rnd_color)
    for x in range(4):
        t.forward(storona)
        t.left(90)
    t.left(360/square)
    storona +=5
Example #48
0
import turtle
import random

sss = input("실행하고싶은 프로그램을 입력해 주십시오:")
if sss == 'invent_Your_own_computer_games_with_python':
    t = turtle.Pen()
    t.penup()

    turtle.bgcolor("black")
    sides = int(turtle.numinput("변의 수",
                                "얼만큼 변의 수를 정하시겠슴니까(2-6)?", 4, 2, 6))
    colors = ["red","yellow","blue","green","orange","purple"]
    for m in range(100):
        t.forward(m * 4)

        position = t.position()
        heading = t.heading()
        print(position,heading)

        for n in range(int(m / 2)):
            t.pendown()
            t.pencolor(colors[n % sides])
            t.forward(n * 2)
            t.right(360 / sides - 2)
            t.penup()
        t.setx(position[0])
        t.sety(position[1])
        t.setheading(heading)
        t.left(360 / sides + 2)
    input("")
Example #49
0
def number_input(env) -> "(title prompt -- n)":
    "Prompts for a number"
    title, prompt = env.stack.popN(2)
    res = turtle.numinput(title.val, prompt.val)
    env.stack.push(Token("lit_float", res if type(res) == float else 0))
color_list = ["red", "yellow", "blue", "green"]

n_colors = len(color_list)

# Get several colors from input
prompt = "Type a color "
for i in range(n_colors):
    new_color = input(prompt)
    color_list[i] = new_color
    print(color_list)
    
# Draw several triangles without lines between them
prompt = "Type a background color "
new_backgroundcolor = input(prompt)
t.bgcolor(new_backgroundcolor)

n = t.numinput("Triangles", "How many", minval = 3, maxval = 30)
n = int(n)

angle = 360 / n
size = 40
c = 0
for i in range(n):
    my_color = color_list[c] 
    color_triangle(size, my_color)
    c = c + 1
    if c >= n_colors: # or (n_colors - 1)
        c = 0
    t.left(angle)
    jump(50)
Example #51
0
import turtle

path = 'C:\\Users\\Jimmy\\Documents\\GitHub\\Computer-Science\\cards\\'

turtle.setup(1920,1080,0,0)

wn = turtle.Screen()
wn.title('Black Jack')
wn.bgcolor('lightblue')

playerOne = turtle.Turtle()

# hides turtle and pen
playerOne.hideturtle()
playerOne.pu()

# sets coordinates
playerOne.setposition(200,0)
playerOne.write('Player Hand',font=('Arial',15))

turtle.register_shape(path + '1.gif')
one = turtle.Turtle(path + '1.gif', visible=False)
one.pu()
one.setposition(0,0)
one.showturtle()

bet = (turtle.numinput('Bet','Enter your bet? ($1-$100)',minval=1, maxval=100))
hit = (turtle.textinput('Hit','Hit or stay (h/s)?'))

wn.mainloop()
Example #52
0
Beans = turtle.Turtle()     #Names the main turtle Beans
Score = turtle.Turtle()     #Names second turtle Score
points = 0

start = 1

while start == 1:       #Loop
    start = 0
    
    #USED TO GET SECONDARY POSITION
    pos1 = randint(-400, 200)       #Used -400 becaue the turtle starts from the lower left part of the square so the lower left points of the window need to be open for the turtle to use.
    pos2 = randint(-400, 200)
    
    startProgram()  #Starts the program
    
    x1 = turtle.numinput("Input", "Input your X coordinate: ")
    y1 = turtle.numinput("Input", "Input your Y coordinate: ")
    
    Beans.goto(x1, y1)  #Goes to input location
    
    if (pos1 + 50) <= (x1) <= (pos1 + 150) and (pos2 + 50) <= (y1) <= (pos2 + 150):     #Turtle is in the small square
        Beans.write("You are in!")
        points += 2     #Add 2 points
        SCORE(points)
        
    elif (pos1 <= (x1) <= (pos1 + 200)) and (pos2 <= (y1) <= (pos2 + 200)):       #Used to see if the turtle is within the square
        Beans.write("Almost there!")
        points += 1     #Add a point
        SCORE(points)
        
    else:       #Turtle did not make it into or onto a square
Example #53
0
# SpiralRosettes.py - a spiral of rosettes!
import turtle
t = turtle.Pen()
t.speed(0)
t.width(2)
t.penup()
turtle.bgcolor("black")
# Ask the user for the number of sides, default to 4, min 2, max 6
sides = int(turtle.numinput("Number of sides",
            "How many sides in your spiral of rosettes? (2-6)", 4,2,6))
colors = ["red", "yellow", "blue", "green", "purple", "orange"]
# Our outer spiral loop
for m in range(100):
    t.forward(m*4)
    position = t.position() # Remember this corner of the spiral
    heading = t.heading()   # Remember the direction we were heading
    print(position, heading)
    t.width(m/20)
    # Our 'inner' spiral loop draws a rosette
    for n in range(sides):
        t.pendown()
        t.pencolor(colors[n%sides])
        t.circle(m/5)
        t.right(360/sides)
        t.penup()
    t.setpos(position)      # Go back to the big spiral's x location
    t.setheading(heading)   # Point in the big spiral's heading
    t.left(360/sides + 2)   # Aim at the next point on the big spiral

           validpic = False
           while not validpic:
                   #Assume they will enter a number between 1 and 9
                   #It will get reset to False if they don't
                   validpic = True;

                   #Validate the user input
                   #nextgo = input('Choose your square: ')
                   #try:
                   #        gopos = int(nextgo) - 1
                   #except ValueError:
                   #        print ('Must be a number')
                   #        validpic = False

                   gopos = int(turtle.numinput("TicTacToe", "Choose your square", 0, 1, 9)) -1

                   if gopos < 0 or gopos > 8:
                        print ('Choose between 1 and 9')
                        validpic = False
                   if not is_free(gopos):
                        print ('space already taken')
                        validpic = False

           board[gopos] = player1char
           x = boardpos[gopos][0]
           y =boardpos[gopos][1]
           drawCross(x,y)


           if check_line (player1char):
# RosetteGoneWild.py
import turtle
t = turtle.Pen()
turtle.bgcolor('black')
t.speed(0)
t.width(3)
# Ask the user for the number of circles in their rosette, default to 6
number_of_circles = int(turtle.numinput("Number of circles",
                                        "How many circles in your rosette?", 6))
color_of_circle = int(turtle.numinput("color of circle",
                                      "What color do you want for first circle",blue)


Example #56
0
import turtle, random

colors = ["red", "orange", "white", "green", "blue", "pink", "purple", "yellow"]
radius = 50


t = turtle.Pen()
t.width(3)
turtle.speed(0)
turtle.bgcolor("black")
circles = int(turtle.numinput("Количество окружностей", "Сколько окружностей нарисовать?",4, 1, 360))
for i in range(circles):
    t.pencolor(random.choice(colors))
    t.circle(radius)
    t.left(360/circles)
    radius +=5
Example #57
0
        t.forward(side_length)
        t.right(angle)
    #end for
        
    return None
#end def

t.speed('fastest')
t.pencolor('blue')

# draw 3 triangles
length = 60
draw_triangle(length)
length = 70
draw_triangle(length)
length = 120
draw_triangle(length)

answer = t.numinput("Triangles", "How many figures to draw in spiral? ")
n = int(answer)

size = 7
extra = 5

for i in range(n):
    draw_triangle(size)
    size = size + extra
    t.right(4)
    t.forward(8)
#end for
# PolygonOrRosette.py
import turtle
t = turtle.Pen()
# Ask the user for the number of sides or circles, default to 6
number = int(turtle.numinput("Number of sides or circles",
             "How many sides or circles in your shape?", 6))
# Ask the user whether they want a polygon or rosette
shape = turtle.textinput("Which shape do you want?",
                         "Enter 'p' for polygon or 'r' for rosette:")
for x in range(number):
    if shape == 'r':        # User selected rosette
        t.circle(100)
    else:                   # Default to polygon
        t.forward(150)
    t.left(360/number)


Example #59
0
turtle.write("Ура! Будем играть! :)", font=("Arial", 20))

# try_count = 0
# tries = 12

#cleaning game progress area
#turtle.color("#1A4876", "white")
# eraser(-375, -75, 250, 250)
# print("test")
# input()
try_count = 0
tries = 11

#starting game
while True:
    number = turtle.numinput("Нужно угадать", "Число 0 до 100", 0, 0, 100)
    if number == x:
        eraser(-375, -75, 250, 250)
        gotoxy(-375, 0)
        turtle.color('blue')
        turtle.write("Поздравляю! ;)", font=("Arial", 18, "normal"))
        break
    else:
        if try_count < 10:
            turtle.color()
            sv_elements[(try_count)]
            gotoxy(50, 200)
            turtle.color('orange')
            turtle.write("Не угадал!", font=("Arial", 15, "normal"))
        elif try_count == 10:
            sv_elements[try_count]
# RainbowRosettes.py
import turtle
import colorsys
t=turtle.Pen()
turtle.bgcolor('black')
t.speed(0)
t.width(3)
# Ask the user for the number of circles in their rosette, default to 30
number_of_circles = int(turtle.numinput("Number of circles",
                                        "How many circles in your rosette?",30))
for x in range(number_of_circles):
    t.pencolor(colorsys.hsv_to_rgb(2*x/number_of_circles,1,1) )
    t.circle(150)
    t.left(360/number_of_circles)