import tkinter as tk
import math
class DroneSubmarineGUI:
def __init__(self, root):
self.root = root
self.root.title("Drone Submarine Controller")
self.canvas = tk.Canvas(root, width=800, height=600, bg='lightblue')
self.canvas.pack()
# Initial Position and Velocity
self.x, self.y = 400, 300
self.vx, self.vy = 0, 0
self.angle = 0
self.speed = 5
self.propeller_speed = 10
# Draw Entities
self.body = self.canvas.create_oval(self.x-50, self.y-20, self.x+50, self.y+20, fill='gray', outline='black')
self.periscope = self.canvas.create_rectangle(self.x-5, self.y-30, self.x+5, self.y-10, fill='darkgray')
# 4-stroke propeller lines
self.prop_lines = []
for i in range(4):
line = self.canvas.create_line(self.x-60, self.y, self.x-80, self.y, width=3, fill='black')
self.prop_lines.append(line)
# Bind Keys
self.root.bind("<KeyPress>", self.keydown)
self.root.bind("<KeyRelease>", self.keyup)
# Start animation
self.animate()
def keydown(self, event):
if event.char == 'w': self.vy = -self.speed
elif event.char == 's': self.vy = self.speed
elif event.char == 'a': self.vx = -self.speed
elif event.char == 'd': self.vx = self.speed
def keyup(self, event):
if event.char in ['w', 's']: self.vy = 0
elif event.char in ['a', 'd']: self.vx = 0
def animate(self):
# Move objects
self.canvas.move(self.body, self.vx, self.vy)
self.canvas.move(self.periscope, self.vx, self.vy)
for line in self.prop_lines:
self.canvas.move(line, self.vx, self.vy)
# Update center coordinates
self.x += self.vx
self.y += self.vy
# Rotate Propeller
self.angle += self.propeller_speed
for i, line in enumerate(self.prop_lines):
# Calculate 4 stroke positions based on angle
a = math.radians(self.angle + (i * 90))
dx = 20 * math.cos(a)
dy = 20 * math.sin(a)
self.canvas.coords(line, self.x-60, self.y, self.x-60+dx, self.y+dy)
self.root.after(20, self.animate)
if __name__ == "__main__":
root = tk.Tk()
app = DroneSubmarineGUI(root)
root.mainloop()

Tidak ada komentar:
Posting Komentar