Python Tkinter - Moving Car by Slope 45 degrees - Gemini AI
PROMPT GEMINI AI :
python tkinter create two little circles wheels animation with 4 stokes rotate and create a brown rectangle attach with them an move right and move go up to a slope 45 degrees
RESULT :
python
importtkinteras tk
importmath# --- Constants ---WIDTH, HEIGHT = 800, 400WHEEL_RADIUS = 15SPOKE_LENGTH = 13RECT_WIDTH = 100RECT_HEIGHT = 40SPEED = 2ANGLE = math.radians(45) # 45 degrees# --- Setup ---root = tk.Tk()
root.title("Moving Car Animation")
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="white")
canvas.pack()
# Initial positionx, y = 50, HEIGHT - 50# --- Create Shapes ---# Rectangle (Body)rect = canvas.create_rectangle(x, y - RECT_HEIGHT, x + RECT_WIDTH, y, fill="brown", outline="brown")
# Wheelswheel1 = canvas.create_oval(x + 10, y - WHEEL_RADIUS, x + 30 + WHEEL_RADIUS, y + WHEEL_RADIUS, fill="black")
wheel2 = canvas.create_oval(x + 70, y - WHEEL_RADIUS, x + 90 + WHEEL_RADIUS, y + WHEEL_RADIUS, fill="black")
# Spokes (Lines for rotation)spokes = []
forwheelin [wheel1, wheel2]:
foriin range(4):
spokes.append(canvas.create_line(0, 0, 0, 0, fill="white", width=2))
# --- Animation Function ---defanimate(angle_deg=0):
global x, y
# Move Right and Up (45 degrees)dx = SPEED * math.cos(ANGLE)
dy = -SPEED * math.sin(ANGLE)
# Update position
x += dx
y += dy
# Reset if goes off-screenif x > WIDTH or y < 0:
x, y = -100, HEIGHT - 50# Move Body
canvas.coords(rect, x, y - RECT_HEIGHT, x + RECT_WIDTH, y)
# Move and Rotate Wheelsfori, wheelin enumerate([wheel1, wheel2]):
offset = 10if i == 0else70wheel_center_x = x + offset + WHEEL_RADIUS
wheel_center_y = y + WHEEL_RADIUS
# Update Wheel Position
canvas.coords(wheel, wheel_center_x - WHEEL_RADIUS, wheel_center_y - WHEEL_RADIUS,
wheel_center_x + WHEEL_RADIUS, wheel_center_y + WHEEL_RADIUS)
# Update Spokesforjin range(4):
spoke_idx = (i * 4) + j
# Rotate spokess_angle = math.radians(angle_deg + (j * 90))
sx = wheel_center_x + SPOKE_LENGTH * math.cos(s_angle)
sy = wheel_center_y + SPOKE_LENGTH * math.sin(s_angle)
canvas.coords(spokes[spoke_idx], wheel_center_x, wheel_center_y, sx, sy)
# Continue Animation
root.after(20, lambda: animate(angle_deg + 10))
# Start
animate()
root.mainloop()
Key Techniques Used
canvas.create_oval & create_rectangle: Used to draw the wheels and body.
canvas.move: Alternatively, canvas.coords is used here to update the exact position of all components (rectangle, wheels, spokes) every frame.
math.cos/math.sin: Calculate the
slope for diagonal movement.
root.after(ms, func): Creates the animation loop by calling the animation function recursively every 2
Tidak ada komentar:
Posting Komentar