some new stuff.
idk its all pretty fun! some C++ too!
This commit is contained in:
60
cube/fibonnacci.py
Normal file
60
cube/fibonnacci.py
Normal file
@@ -0,0 +1,60 @@
|
||||
import math
|
||||
import tkinter as tk
|
||||
|
||||
class Fibonacci:
|
||||
def s5(self, n, r):
|
||||
"""Generate Fibonacci spiral polar coordinates"""
|
||||
spirals = []
|
||||
phi = (1 + 5 ** 0.5) / 2 # golden ratio
|
||||
for i in range(n + 1):
|
||||
angle = (i * 360 / phi) % 360
|
||||
spirals.append((r * (i ** 0.5), angle))
|
||||
return spirals
|
||||
|
||||
def pol2cart(self, r, theta):
|
||||
x = r * math.cos(math.radians(theta))
|
||||
y = r * math.sin(math.radians(theta))
|
||||
return x, y
|
||||
|
||||
def calculate_coordinates(self, num_points=200, distance=15):
|
||||
# Convert polar to Cartesian coordinates
|
||||
self.coordinates = [self.pol2cart(r, t) for r, t in self.s5(num_points, distance)]
|
||||
# Center for the canvas
|
||||
self.coordinates = [(x + 250, y + 250) for x, y in self.coordinates]
|
||||
|
||||
def plot_numbers(self, canvas):
|
||||
self.calculate_coordinates()
|
||||
for idx, (x, y) in enumerate(self.coordinates, start=1):
|
||||
canvas.create_oval(x - 7, y - 7, x + 7, y + 7, fill="white")
|
||||
canvas.create_text(x, y, text=str(idx))
|
||||
|
||||
def plot_lines(self, canvas):
|
||||
for delta in [21, 34]:
|
||||
for start in range(34):
|
||||
x0, y0 = self.coordinates[start]
|
||||
i = start + delta
|
||||
while i < len(self.coordinates):
|
||||
x1, y1 = self.coordinates[i]
|
||||
canvas.create_line(x0, y0, x1, y1)
|
||||
x0, y0 = x1, y1
|
||||
i += delta
|
||||
|
||||
def create_gui(self):
|
||||
master = tk.Tk()
|
||||
master.title("Fibonacci Spiral")
|
||||
canvas = tk.Canvas(master, width=500, height=500, bg="white")
|
||||
canvas.pack()
|
||||
|
||||
self.plot_numbers(canvas)
|
||||
self.plot_lines(canvas)
|
||||
|
||||
master.mainloop()
|
||||
|
||||
|
||||
def main():
|
||||
f = Fibonacci()
|
||||
f.create_gui()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
142
cube/main.py
Normal file
142
cube/main.py
Normal file
@@ -0,0 +1,142 @@
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
from matplotlib.animation import FuncAnimation
|
||||
from matplotlib.widgets import Button
|
||||
|
||||
cube_points = np.array([
|
||||
[-1, -1, -1],
|
||||
[-1, -1, 1],
|
||||
[-1, 1, -1],
|
||||
[-1, 1, 1],
|
||||
[ 1, -1, -1],
|
||||
[ 1, -1, 1],
|
||||
[ 1, 1, -1],
|
||||
[ 1, 1, 1]
|
||||
])
|
||||
|
||||
edges = [
|
||||
(0, 1), (0, 2), (0, 4),
|
||||
(1, 3), (1, 5),
|
||||
(2, 3), (2, 6),
|
||||
(3, 7),
|
||||
(4, 5), (4, 6),
|
||||
(5, 7),
|
||||
(6, 7)
|
||||
]
|
||||
|
||||
def rotation_y(theta):
|
||||
return np.array([
|
||||
[np.cos(theta), 0, np.sin(theta)],
|
||||
[0, 1, 0], # 0,1,0
|
||||
[-np.sin(theta), 0, np.cos(theta)]
|
||||
])
|
||||
|
||||
|
||||
def rotation_z(theta):
|
||||
return np.array([
|
||||
[np.cos(theta), -np.sin(theta), 0],
|
||||
[np.sin(theta), np.cos(theta), 0],
|
||||
[0, 0, 1]
|
||||
])
|
||||
|
||||
|
||||
fig = plt.figure(figsize=(8, 6))
|
||||
ax = fig.add_subplot(111, projection='3d')
|
||||
ax.set_xlim(-2, 2)
|
||||
ax.set_ylim(-2, 2)
|
||||
ax.set_zlim(-2, 2)
|
||||
ax.set_box_aspect([1, 1, 1])
|
||||
ax.set_title("Matrixmultiplikation", pad=20)
|
||||
|
||||
lines = [ax.plot([], [], [], color='red')[0] for _ in edges]
|
||||
text = ax.text2D(1.02, 0.5, "", transform=ax.transAxes,
|
||||
fontsize=10, color='black', family='monospace', va='center')
|
||||
|
||||
paused = False
|
||||
highlight = False
|
||||
points_scat = None
|
||||
labels = []
|
||||
|
||||
|
||||
def update(frame):
|
||||
global points_scat, labels
|
||||
|
||||
if paused:
|
||||
return lines + [text]
|
||||
|
||||
theta = np.radians(frame)
|
||||
R_y = rotation_y(theta)
|
||||
R_z = rotation_z(theta * 0.7)
|
||||
R = R_y @ R_z
|
||||
|
||||
rotated = cube_points @ R.T
|
||||
|
||||
# Update edges
|
||||
for line, (i1, i2) in zip(lines, edges):
|
||||
p1, p2 = rotated[i1], rotated[i2]
|
||||
line.set_data([p1[0], p2[0]], [p1[1], p2[1]])
|
||||
line.set_3d_properties([p1[2], p2[2]])
|
||||
|
||||
# Update rotation matrices display
|
||||
matrix_str_y = "\n".join(
|
||||
["[" + " ".join(f"{val:+.2f}" for val in row) + "]" for row in R_y]
|
||||
)
|
||||
matrix_str_z = "\n".join(
|
||||
["[" + " ".join(f"{val:+.2f}" for val in row) + "]" for row in R_z]
|
||||
)
|
||||
matrix_str_R = "\n".join(
|
||||
["[" + " ".join(f"{val:+.2f}" for val in row) + "]" for row in R]
|
||||
)
|
||||
|
||||
text.set_text(
|
||||
f"θ = {np.degrees(theta):6.2f}°\n"
|
||||
f"sin(θ) = {np.sin(theta): .3f}\n"
|
||||
f"cos(θ) = {np.cos(theta): .3f}\n\n"
|
||||
f"R_y(θ):\n{matrix_str_y}\n\n"
|
||||
f"R_z(0.7θ):\n{matrix_str_z}\n\n"
|
||||
f"R = R_y · R_z:\n{matrix_str_R}"
|
||||
)
|
||||
|
||||
# Always show vertex points and labels
|
||||
if points_scat is None:
|
||||
points_scat = ax.scatter([], [], [], color='blue', s=40)
|
||||
|
||||
points_scat._offsets3d = (
|
||||
rotated[:, 0], rotated[:, 1], rotated[:, 2]
|
||||
)
|
||||
|
||||
for label in labels:
|
||||
label.remove()
|
||||
labels.clear()
|
||||
|
||||
for i, p in enumerate(rotated):
|
||||
labels.append(ax.text(p[0], p[1], p[2], f"P{i}",
|
||||
color='black', fontsize=8))
|
||||
|
||||
return lines + [text]
|
||||
|
||||
|
||||
|
||||
axpause = plt.axes([0.4, 0.02, 0.3, 0.05])
|
||||
bpause = Button(axpause, 'Pause / Resume')
|
||||
|
||||
|
||||
def toggle_pause(event):
|
||||
global paused
|
||||
paused = not paused
|
||||
|
||||
|
||||
def toggle_highlight(event):
|
||||
global highlight
|
||||
highlight = not highlight
|
||||
|
||||
|
||||
bpause.on_clicked(toggle_pause)
|
||||
|
||||
ani = FuncAnimation(
|
||||
fig, update, frames=np.arange(0, 360, 2),
|
||||
interval=50, blit=False
|
||||
)
|
||||
|
||||
plt.show()
|
||||
52
cube/pattern.py
Normal file
52
cube/pattern.py
Normal file
@@ -0,0 +1,52 @@
|
||||
import pygame
|
||||
import math
|
||||
import sys
|
||||
|
||||
# --- Pygame setup ---
|
||||
pygame.init()
|
||||
WIDTH, HEIGHT = 800, 800
|
||||
screen = pygame.display.set_mode((WIDTH, HEIGHT))
|
||||
clock = pygame.time.Clock()
|
||||
|
||||
# --- Colors ---
|
||||
BLACK = (0, 0, 0)
|
||||
colors = [(255, 100, 100), (100, 255, 150), (100, 150, 255), (255, 255, 100)]
|
||||
|
||||
# --- Fibonacci sequence generator ---
|
||||
def fibonacci(n):
|
||||
fibs = [0, 1]
|
||||
for i in range(2, n):
|
||||
fibs.append(fibs[-1] + fibs[-2])
|
||||
return fibs
|
||||
|
||||
# --- Spiral drawing ---
|
||||
def draw_fibonacci_spiral(n, angle_offset):
|
||||
fibs = fibonacci(n)
|
||||
cx, cy = WIDTH//2, HEIGHT//2
|
||||
scale = 0.05 # scale down Fibonacci numbers to fit screen
|
||||
|
||||
for i, f in enumerate(fibs[1:], 1): # skip the first 0
|
||||
angle = i * 137.5 + angle_offset # golden angle in degrees
|
||||
rad = math.radians(angle)
|
||||
x = cx + f * math.cos(rad) * scale
|
||||
y = cy + f * math.sin(rad) * scale
|
||||
color = colors[i % len(colors)]
|
||||
pygame.draw.circle(screen, color, (int(x), int(y)), max(int(f*scale*0.5)+2, 2))
|
||||
|
||||
# --- Main loop ---
|
||||
angle_offset = 0
|
||||
running = True
|
||||
while running:
|
||||
screen.fill(BLACK)
|
||||
draw_fibonacci_spiral(50, angle_offset)
|
||||
angle_offset += 1 # rotate the spiral over time
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
|
||||
pygame.display.flip()
|
||||
clock.tick(60)
|
||||
|
||||
pygame.quit()
|
||||
sys.exit()
|
||||
173
cube/tktcl.py
Normal file
173
cube/tktcl.py
Normal file
@@ -0,0 +1,173 @@
|
||||
"""
|
||||
rotating_cube_tk.py
|
||||
|
||||
Simple Tkinter app that rotates a 3D cube using rotation matrices along X and Z axes.
|
||||
No dependencies outside the Python standard library.
|
||||
"""
|
||||
|
||||
import tkinter as tk
|
||||
import math
|
||||
import time
|
||||
|
||||
# Canvas size
|
||||
W, H = 700, 700
|
||||
|
||||
# Cube definition (8 vertices of a cube centered at origin)
|
||||
size = 150
|
||||
vertices = [
|
||||
(-1, -1, -1),
|
||||
(-1, -1, 1),
|
||||
(-1, 1, -1),
|
||||
(-1, 1, 1),
|
||||
( 1, -1, -1),
|
||||
( 1, -1, 1),
|
||||
( 1, 1, -1),
|
||||
( 1, 1, 1),
|
||||
]
|
||||
# Scale vertices by size
|
||||
vertices = [(x * size, y * size, z * size) for (x, y, z) in vertices]
|
||||
|
||||
# Edges connecting vertices (pairs of indices)
|
||||
edges = [
|
||||
(0,1), (0,2), (0,4),
|
||||
(1,3), (1,5),
|
||||
(2,3), (2,6),
|
||||
(3,7),
|
||||
(4,5), (4,6),
|
||||
(5,7),
|
||||
(6,7),
|
||||
]
|
||||
|
||||
# Rotation speeds (radians per frame)
|
||||
rot_speed_x = 0.02
|
||||
rot_speed_z = 0.015
|
||||
|
||||
# Perspective parameters
|
||||
viewer_distance = 600 # Larger -> weaker perspective
|
||||
fov = 500 # Field of view scaling
|
||||
|
||||
class CubeApp:
|
||||
def __init__(self, master):
|
||||
self.master = master
|
||||
master.title("3D Rotating Cube (X and Z rotation matrices)")
|
||||
|
||||
self.canvas = tk.Canvas(master, width=W, height=H, bg="white")
|
||||
self.canvas.pack(fill="both", expand=True)
|
||||
|
||||
# angles
|
||||
self.ang_x = 0.0
|
||||
self.ang_z = 0.0
|
||||
|
||||
# control
|
||||
self.paused = False
|
||||
self.last_time = time.time()
|
||||
|
||||
# drawn items (to update instead of recreating shapes each frame)
|
||||
self.line_ids = []
|
||||
for _ in edges:
|
||||
self.line_ids.append(self.canvas.create_line(0,0,0,0, width=2))
|
||||
|
||||
# instructions text
|
||||
self.canvas.create_text(10, 10, anchor="nw",
|
||||
text="Space: pause/resume Up/Down: speed X Left/Right: speed Z",
|
||||
fill="black", font=("Helvetica", 10))
|
||||
|
||||
# Bind keys
|
||||
master.bind("<space>", self.toggle_pause)
|
||||
master.bind("<Up>", self.speed_up_x)
|
||||
master.bind("<Down>", self.speed_down_x)
|
||||
master.bind("<Right>", self.speed_up_z)
|
||||
master.bind("<Left>", self.speed_down_z)
|
||||
|
||||
# Start animation
|
||||
self.animate()
|
||||
|
||||
# Rotation matrix around X for angle a
|
||||
def rotate_x(self, point, a):
|
||||
x, y, z = point
|
||||
cos_a = math.cos(a)
|
||||
sin_a = math.sin(a)
|
||||
y2 = y * cos_a - z * sin_a
|
||||
z2 = y * sin_a + z * cos_a
|
||||
return (x, y2, z2)
|
||||
|
||||
# Rotation matrix around Z for angle a
|
||||
def rotate_z(self, point, a):
|
||||
x, y, z = point
|
||||
cos_a = math.cos(a)
|
||||
sin_a = math.sin(a)
|
||||
x2 = x * cos_a - y * sin_a
|
||||
y2 = x * sin_a + y * cos_a
|
||||
return (x2, y2, z)
|
||||
|
||||
# Project 3D point to 2D using simple perspective
|
||||
def project(self, point):
|
||||
x, y, z = point
|
||||
# shift z relative to viewer so we don't divide by zero
|
||||
z_shifted = z + viewer_distance
|
||||
if z_shifted == 0:
|
||||
z_shifted = 0.0001
|
||||
factor = fov / z_shifted
|
||||
x_proj = x * factor + W/2
|
||||
y_proj = -y * factor + H/2 # invert y for screen coords
|
||||
return (x_proj, y_proj)
|
||||
|
||||
def animate(self):
|
||||
# compute time delta for smoother animation (in case of slow frame)
|
||||
now = time.time()
|
||||
dt = now - self.last_time
|
||||
self.last_time = now
|
||||
|
||||
if not self.paused:
|
||||
# update angles (scale by dt to be time-based)
|
||||
self.ang_x += rot_speed_x * (dt * 60) # adjust to feel like frame-based speeds
|
||||
self.ang_z += rot_speed_z * (dt * 60)
|
||||
|
||||
# compute rotated points
|
||||
rotated = []
|
||||
for v in vertices:
|
||||
r = self.rotate_x(v, self.ang_x)
|
||||
r = self.rotate_z(r, self.ang_z)
|
||||
rotated.append(r)
|
||||
|
||||
# project all points
|
||||
projected = [self.project(p) for p in rotated]
|
||||
|
||||
# draw edges by updating canvas lines
|
||||
for i, (a, b) in enumerate(edges):
|
||||
x1, y1 = projected[a]
|
||||
x2, y2 = projected[b]
|
||||
# update existing line coordinates
|
||||
self.canvas.coords(self.line_ids[i], x1, y1, x2, y2)
|
||||
|
||||
# optionally: draw small circles at vertices (commented out to keep it clean)
|
||||
for (x, y) in projected:
|
||||
self.canvas.create_oval(x-3, y-3, x+3, y+3, fill="black")
|
||||
|
||||
# schedule next frame (aiming ~60 FPS)
|
||||
self.master.after(1, self.animate)
|
||||
|
||||
# Controls
|
||||
def toggle_pause(self, event=None):
|
||||
self.paused = not self.paused
|
||||
|
||||
def speed_up_x(self, event=None):
|
||||
global rot_speed_x
|
||||
rot_speed_x += 0.005
|
||||
|
||||
def speed_down_x(self, event=None):
|
||||
global rot_speed_x
|
||||
rot_speed_x -= 0.005
|
||||
|
||||
def speed_up_z(self, event=None):
|
||||
global rot_speed_z
|
||||
rot_speed_z += 0.005
|
||||
|
||||
def speed_down_z(self, event=None):
|
||||
global rot_speed_z
|
||||
rot_speed_z -= 0.005
|
||||
|
||||
if __name__ == "__main__":
|
||||
root = tk.Tk()
|
||||
app = CubeApp(root)
|
||||
root.mainloop()
|
||||
Reference in New Issue
Block a user