【问题标题】:How can I draw in Turtle given speed and angle value?给定速度和角度值,如何在 Turtle 中绘制?
【发布时间】:2021-11-27 15:38:27
【问题描述】:

先看my code。如果你运行它,程序会看起来像like this

所以,我的问题是:我必须输入速度和角度值并按下按钮来启动它,但我不知道该怎么做。我现在想到的是

(int(speed1.get())*math.cos(int(angle1.get())))*(int(speed1.get())*math.sin(int(angle1.get()))/4.9)

我想我需要使用它。 if d > 25:是决心,所以不知道要不要把公式放在d里。

我该怎么做?

【问题讨论】:

标签: python tkinter python-turtle


【解决方案1】:

我发现您的代码存在几个问题。首先,您是在使用 standalone turtle 和 tkinter。在 tkinter 程序中嵌入 turtle 时,需要使用 embedded turtle,即 RawTurtle 代替 TurtleTurtleScreen 代替 Screen 等。否则,你有两个根源和奇怪的问题会出现。

其次,您需要某种弹道逻辑,仅计算角度是不够的。此外,您必须清楚哪些角度是 degrees(例如,可能是用户输入;默认情况下海龟想要什么)与 radiansma​​th.py 图书馆需要。)

最后,在 tkinter 接口和海龟输出之间传递值的一种方法是使用与 Entry 小部件关联的 IntVar 值。这是我对解决上述问题的代码的(可能有错误的)返工:

from tkinter import *
from turtle import TurtleScreen, RawTurtle
from random import randint
from math import sin, cos, radians

x0, y0 = -200, 10  # initial location

g = 11.0  # acceleration due to gravity in units per second squared

def fire():
    a = angle.get()
    turtle.setheading(a)

    v = velocity.get()

    vx, vy = cos(radians(a)) * v, sin(radians(a)) * v  # initial velocity in units per second

    for t in range(1, 10_000):

        x = x0 + vx * t
        y = y0 + vy * t - g / 2 * t**2

        turtle.goto(x, y)

        if y < y0:
            break

    distance = turtle.distance(target, y0)

    if distance < 25:
        turtle.color('blue')
        turtle.write("HIT", align='center', font=('', 10))
    else:
        turtle.color('red')
        turtle.write("MISS", align='center', font=('', 10))

    turtle.color('black')
    turtle.goto(x0, y0)
    turtle.setheading(0)

window = Tk()
window.geometry("+250+150")
window.title("Ballistics")

canvas = Canvas(window, width=600, height=300)
canvas.pack() # fill="both", expand=True)

screen = TurtleScreen(canvas)
turtle = RawTurtle(screen)

turtle.penup()
turtle.setx(-300)
turtle.pendown()
turtle.setx(300)

target = randint(50, 150)

turtle.pensize(3)
turtle.color('green')
turtle.penup()
turtle.goto(target - 25, 2)
turtle.pendown()
turtle.goto(target + 25, 2)

turtle.color('black')
turtle.pensize(2)
turtle.penup()
turtle.goto(x0, y0)

menu = Toplevel(window)
menu.geometry("200x150")
menu.title("Menu")

velocity = IntVar()
Label(menu, text="Velocity").pack()
Entry(menu, textvariable=velocity).pack()

angle = IntVar()
Label(menu, text="Angle").pack()
Entry(menu, textvariable=angle).pack()

Button(menu, text="Fire", command=fire).pack()

window.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多