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=600, height=400, bg="skyblue")
self.canvas.pack()
# Start button
self.start_btn = tk.Button(root, text="Start Quadcopter", command=self.start_animation)
self.start_btn.pack(pady=10)
# Quadcopter properties
self.center_x = 300
self.center_y = 200
self.body_radius = 20
self.propeller_length = 15
self.propeller_angle = 0
self.speed = 5
self.running = False
# Bind keyboard controls
self.root.bind("<KeyPress>", self.key_press)
def draw_quadcopter(self):
"""Draws the quadcopter body and propellers."""
self.canvas.delete("all")
# Draw body
self.canvas.create_oval(
self.center_x - self.body_radius, self.center_y - self.body_radius,
self.center_x + self.body_radius, self.center_y + self.body_radius,
fill="gray", outline="black", width=2
)
# Propeller positions (relative to body)
offsets = [
(-self.body_radius - 10, -self.body_radius - 10), # top-left
(self.body_radius + 10, -self.body_radius - 10), # top-right
(-self.body_radius - 10, self.body_radius + 10), # bottom-left
(self.body_radius + 10, self.body_radius + 10) # bottom-right
]
for dx, dy in offsets:
cx = self.center_x + dx
cy = self.center_y + dy
self.draw_rotating_propeller(cx, cy)
def draw_rotating_propeller(self, cx, cy):
"""Draws a rotating propeller at given center."""
angle_rad = math.radians(self.propeller_angle)
for i in range(2): # Two blades per propeller
blade_angle = angle_rad + i * math.pi / 2
x1 = cx - self.propeller_length * math.cos(blade_angle)
y1 = cy - self.propeller_length * math.sin(blade_angle)
x2 = cx + self.propeller_length * math.cos(blade_angle)
y2 = cy + self.propeller_length * math.sin(blade_angle)
self.canvas.create_line(x1, y1, x2, y2, fill="black", width=2)
def update_animation(self):
"""Updates propeller rotation and redraws quadcopter."""
if self.running:
self.propeller_angle = (self.propeller_angle + 15) % 360
self.draw_quadcopter()
self.root.after(50, self.update_animation) # 20 FPS
def start_animation(self):
"""Starts the quadcopter animation."""
if not self.running:
self.running = True
self.update_animation()
def key_press(self, event):
"""Handles movement with WASD keys."""
if not self.running:
return
key = event.keysym.lower()
if key == "w":
self.center_y -= self.speed
elif key == "s":
self.center_y += self.speed
elif key == "a":
self.center_x -= self.speed
elif key == "d":
self.center_x += self.speed
# Keep quadcopter inside canvas bounds
self.center_x = max(self.body_radius, min(600 - self.body_radius, self.center_x))
self.center_y = max(self.body_radius, min(400 - self.body_radius, self.center_y))
self.draw_quadcopter()
# Run the app
if __name__ == "__main__":
root = tk.Tk()
app = QuadcopterApp(root)
root.mainloop()

Tidak ada komentar:
Posting Komentar