import tkinter as tk
import math
class QuadcopterApp:
def __init__(self, root):
self.root = root
self.root.title("Quadcopter Animation")
# Canvas setup
self.canvas = tk.Canvas(root, width=800, height=600, bg="skyblue")
self.canvas.pack()
# Start button
self.start_btn = tk.Button(root, text="Start", command=self.start_animation)
self.start_btn.pack(pady=5)
# Quadcopter state
self.x = 400
self.y = 300
self.size = 60
self.prop_angle = 0
self.running = False
self.speed = 5
# Bind keyboard controls
self.root.bind("<KeyPress>", self.on_key_press)
def start_animation(self):
if not self.running:
self.running = True
self.animate()
def on_key_press(self, event):
"""Handle WASD movement"""
if event.char.lower() == 'w':
self.y -= self.speed
elif event.char.lower() == 's':
self.y += self.speed
elif event.char.lower() == 'a':
self.x -= self.speed
elif event.char.lower() == 'd':
self.x += self.speed
def draw_quadcopter(self):
"""Draw the quadcopter body and propellers"""
self.canvas.delete("all")
# Draw body (center rectangle)
body_size = self.size // 2
self.canvas.create_rectangle(
self.x - body_size, self.y - body_size,
self.x + body_size, self.y + body_size,
fill="gray", outline="black"
)
# Arm length
arm_len = self.size
prop_radius = 12
# Propeller positions (relative to center)
offsets = [
(-arm_len, -arm_len), # top-left
(arm_len, -arm_len), # top-right
(-arm_len, arm_len), # bottom-left
(arm_len, arm_len) # bottom-right
]
for dx, dy in offsets:
cx = self.x + dx
cy = self.y + dy
# Draw arm
self.canvas.create_line(self.x, self.y, cx, cy, width=3, fill="black")
# Draw rotating propeller
angle1 = math.radians(self.prop_angle)
angle2 = math.radians(self.prop_angle + 90)
x1 = cx + prop_radius * math.cos(angle1)
y1 = cy + prop_radius * math.sin(angle1)
x2 = cx - prop_radius * math.cos(angle1)
y2 = cy - prop_radius * math.sin(angle1)
x3 = cx + prop_radius * math.cos(angle2)
y3 = cy + prop_radius * math.sin(angle2)
x4 = cx - prop_radius * math.cos(angle2)
y4 = cy - prop_radius * math.sin(angle2)
self.canvas.create_line(x1, y1, x2, y2, width=2, fill="black")
self.canvas.create_line(x3, y3, x4, y4, width=2, fill="black")
def animate(self):
"""Update animation frame"""
if self.running:
self.prop_angle = (self.prop_angle + 20) % 360
self.draw_quadcopter()
self.root.after(50, self.animate) # ~20 FPS
if __name__ == "__main__":
root = tk.Tk()
app = QuadcopterApp(root)
root.mainloop()

Tidak ada komentar:
Posting Komentar