Guest User

social media connections visual sim

a guest
Dec 2nd, 2026
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.92 KB | Source Code | 0 0
  1. """
  2. Ray-firing circles  (standard library only: tkinter for drawing)
  3.  
  4. Rules
  5. -----
  6. Firing rate
  7.    Each circle fires as a Poisson process whose rate depends on how close its
  8.    nearest neighbour is:
  9.        rate = BASE_RATE + (MAX_RATE - BASE_RATE) * 2 ** (-d_nearest / RATE_HALF_DIST)
  10.    So an isolated circle fires about BASE_RATE times/s, and one with a neighbour
  11.    right on top of it fires close to MAX_RATE times/s.
  12.  
  13. Choosing a direction
  14.    1. With probability UPFRONT_RANDOM, fire in a uniformly random direction.
  15.    2. Otherwise pick one option, weighted:
  16.         - every other circle j has weight 2 ** (-d_j / TARGET_HALF_DIST)
  17.         - "random direction" has weight 1, as if it were a neighbour at
  18.           distance 0 (sitting right on top of the firer).
  19.       Picking a circle fires straight at it; picking "random" fires in a
  20.       uniformly random direction.
  21.    Example (half-distance = 1 unit): 8 neighbours at 3 units each have weight
  22.    1/8, so after step 1 each gets 1/16 and random gets 1/2.
  23.  
  24. Hits
  25.    A circle hit by a ray gets a velocity kick of PULL_IMPULSE toward the
  26.    circle that fired it.
  27.  
  28. Ray colours
  29.    blue    random, decided up front (step 1)
  30.    violet  random, chosen in the weighted draw (step 2)
  31.    orange  aimed at a circle
  32.  
  33. Sliders
  34.    firing rate  MAX_RATE: shots/s a circle fires when a neighbour is right on top of it
  35.    friction     DAMPING: velocity shrinks by a factor exp(-friction) every second
  36.  
  37. Controls
  38.    Space  pause/resume    R  reset    C  toggle circle-circle collisions
  39.    Esc    quit
  40. """
  41.  
  42. import math
  43. import random
  44.  
  45. # ---------------------------------------------------------------- settings
  46. WIDTH, HEIGHT = 1000, 700
  47. FPS = 60
  48.  
  49. NUM_CIRCLES = 60
  50. RADIUS = 5
  51.  
  52. # firing rate (shots per second per circle)
  53. BASE_RATE = 0.4
  54. MAX_RATE = 8.0
  55. RATE_HALF_DIST = 25.0      # px: rate boost halves for every this-many px to the nearest neighbour
  56.  
  57. # targeting
  58. UPFRONT_RANDOM = 0.10
  59. TARGET_HALF_DIST = 25.0    # px: a neighbour's weight halves for every this-many px of distance
  60.  
  61. # rays
  62. RAY_SPEED = 1800.0         # px / s
  63. RAY_STREAK = 30.0          # drawn length, px
  64.  
  65. # motion
  66. PULL_IMPULSE = 18.0        # px/s added toward the firer on a hit
  67. DAMPING = 2.0              # v *= exp(-DAMPING * dt)
  68. MAX_SPEED = 400.0
  69. START_SPEED = 20.0
  70.  
  71. COLLISIONS = False         # circle-circle collisions (toggle with C)
  72.  
  73. BG = "#0c0e16"
  74. CIRCLE_COLOR = "#c8cddc"
  75. COLOR_UPFRONT = "#5ac8ff"
  76. COLOR_WEIGHTED_RANDOM = "#b48cff"
  77. COLOR_AIMED = "#ff963c"
  78. TEXT_COLOR = "#969bab"
  79.  
  80. UPFRONT, WEIGHTED_RANDOM, AIMED = 0, 1, 2
  81. RAY_COLORS = {UPFRONT: COLOR_UPFRONT,
  82.               WEIGHTED_RANDOM: COLOR_WEIGHTED_RANDOM,
  83.               AIMED: COLOR_AIMED}
  84.  
  85.  
  86. # ---------------------------------------------------------------- model
  87. class Circle:
  88.     __slots__ = ("x", "y", "vx", "vy")
  89.  
  90.     def __init__(self, x, y):
  91.         self.x, self.y = x, y
  92.         a = random.uniform(0, math.tau)
  93.         s = random.uniform(0, START_SPEED)
  94.         self.vx, self.vy = math.cos(a) * s, math.sin(a) * s
  95.  
  96.  
  97. class Ray:
  98.     __slots__ = ("owner", "x", "y", "dx", "dy", "kind", "alive")
  99.  
  100.     def __init__(self, owner, x, y, dx, dy, kind):
  101.         self.owner = owner
  102.         self.x, self.y = x, y
  103.         self.dx, self.dy = dx, dy
  104.         self.kind = kind
  105.         self.alive = True
  106.  
  107.  
  108. def segment_hit_t(x0, y0, x1, y1, cx, cy, r):
  109.     """Smallest t in [0,1] where segment (x0,y0)->(x1,y1) touches the circle, else None."""
  110.     fx, fy = x0 - cx, y0 - cy
  111.     dx, dy = x1 - x0, y1 - y0
  112.     a = dx * dx + dy * dy
  113.     c = fx * fx + fy * fy - r * r
  114.     if c <= 0:
  115.         return 0.0
  116.     if a == 0:
  117.         return None
  118.     b = 2 * (fx * dx + fy * dy)
  119.     disc = b * b - 4 * a * c
  120.     if disc < 0:
  121.         return None
  122.     t = (-b - math.sqrt(disc)) / (2 * a)
  123.     return t if 0.0 <= t <= 1.0 else None
  124.  
  125.  
  126. class Sim:
  127.     def __init__(self):
  128.         self.collisions = COLLISIONS
  129.         self.max_rate = MAX_RATE    # adjustable at runtime ("firing rate" slider)
  130.         self.damping = DAMPING      # adjustable at runtime ("friction" slider)
  131.         self.reset()
  132.  
  133.     def reset(self):
  134.         self.circles = [Circle(random.uniform(RADIUS, WIDTH - RADIUS),
  135.                                random.uniform(RADIUS, HEIGHT - RADIUS))
  136.                         for _ in range(NUM_CIRCLES)]
  137.         self.rays = []
  138.         self.shots = {UPFRONT: 0, WEIGHTED_RANDOM: 0, AIMED: 0}
  139.         self.hits = 0
  140.  
  141.     # -- firing ------------------------------------------------------
  142.     def choose_direction(self, i, dists):
  143.         """dists[j] = distance from circle i to circle j. Returns (dx, dy, kind)."""
  144.         if random.random() < UPFRONT_RANDOM:
  145.             a = random.uniform(0, math.tau)
  146.             return math.cos(a), math.sin(a), UPFRONT
  147.  
  148.         # weight 1 for "random" (a phantom neighbour at distance 0)
  149.         total = 1.0
  150.         weights = []
  151.         for j, d in enumerate(dists):
  152.             w = 0.0 if j == i else 2.0 ** (-d / TARGET_HALF_DIST)
  153.             weights.append(w)
  154.             total += w
  155.         pick = random.random() * total
  156.         if pick >= 1.0:
  157.             pick -= 1.0
  158.             for j, w in enumerate(weights):
  159.                 if pick < w:
  160.                     me, other = self.circles[i], self.circles[j]
  161.                     tx, ty = other.x - me.x, other.y - me.y
  162.                     d = math.hypot(tx, ty)
  163.                     if d > 1e-9:
  164.                         return tx / d, ty / d, AIMED
  165.                     break  # exactly coincident: no defined direction, fall through
  166.                 pick -= w
  167.         a = random.uniform(0, math.tau)
  168.         return math.cos(a), math.sin(a), WEIGHTED_RANDOM
  169.  
  170.     def fire(self, i, dists):
  171.         c = self.circles[i]
  172.         dx, dy, kind = self.choose_direction(i, dists)
  173.         sx, sy = c.x + dx * (RADIUS + 0.5), c.y + dy * (RADIUS + 0.5)
  174.         self.rays.append(Ray(i, sx, sy, dx, dy, kind))
  175.         self.shots[kind] += 1
  176.  
  177.     # -- step --------------------------------------------------------
  178.     def step(self, dt):
  179.         cs = self.circles
  180.         n = len(cs)
  181.  
  182.         # pairwise distances (needed for firing rate and targeting)
  183.         dist = [[0.0] * n for _ in range(n)]
  184.         for i in range(n):
  185.             a = cs[i]
  186.             row = dist[i]
  187.             for j in range(i + 1, n):
  188.                 b = cs[j]
  189.                 d = math.hypot(b.x - a.x, b.y - a.y)
  190.                 row[j] = d
  191.                 dist[j][i] = d
  192.  
  193.         for i in range(n):
  194.             nearest = min(d for j, d in enumerate(dist[i]) if j != i) if n > 1 else math.inf
  195.             rate = BASE_RATE + max(0.0, self.max_rate - BASE_RATE) * 2.0 ** (-nearest / RATE_HALF_DIST)
  196.             if random.random() < 1.0 - math.exp(-rate * dt):
  197.                 self.fire(i, dist[i])
  198.  
  199.         # move rays, swept collision test
  200.         for ray in self.rays:
  201.             step = RAY_SPEED * dt
  202.             nx, ny = ray.x + ray.dx * step, ray.y + ray.dy * step
  203.             best_t, best_j = None, None
  204.             for j, c in enumerate(cs):
  205.                 if j == ray.owner:
  206.                     continue
  207.                 t = segment_hit_t(ray.x, ray.y, nx, ny, c.x, c.y, RADIUS)
  208.                 if t is not None and (best_t is None or t < best_t):
  209.                     best_t, best_j = t, j
  210.             if best_j is not None:
  211.                 target, firer = cs[best_j], cs[ray.owner]
  212.                 px, py = firer.x - target.x, firer.y - target.y
  213.                 d = math.hypot(px, py)
  214.                 if d > 1e-9:
  215.                     target.vx += px / d * PULL_IMPULSE
  216.                     target.vy += py / d * PULL_IMPULSE
  217.                 ray.alive = False
  218.                 self.hits += 1
  219.                 continue
  220.             ray.x, ray.y = nx, ny
  221.             if not (-RAY_STREAK <= nx <= WIDTH + RAY_STREAK and
  222.                     -RAY_STREAK <= ny <= HEIGHT + RAY_STREAK):
  223.                 ray.alive = False
  224.         self.rays = [r for r in self.rays if r.alive]
  225.  
  226.         # move circles
  227.         decay = math.exp(-self.damping * dt)
  228.         for c in cs:
  229.             c.vx *= decay
  230.             c.vy *= decay
  231.             sp = math.hypot(c.vx, c.vy)
  232.             if sp > MAX_SPEED:
  233.                 c.vx *= MAX_SPEED / sp
  234.                 c.vy *= MAX_SPEED / sp
  235.             c.x += c.vx * dt
  236.             c.y += c.vy * dt
  237.             if c.x < RADIUS:
  238.                 c.x, c.vx = RADIUS, abs(c.vx)
  239.             elif c.x > WIDTH - RADIUS:
  240.                 c.x, c.vx = WIDTH - RADIUS, -abs(c.vx)
  241.             if c.y < RADIUS:
  242.                 c.y, c.vy = RADIUS, abs(c.vy)
  243.             elif c.y > HEIGHT - RADIUS:
  244.                 c.y, c.vy = HEIGHT - RADIUS, -abs(c.vy)
  245.  
  246.         if self.collisions:
  247.             self.resolve_collisions()
  248.  
  249.     def resolve_collisions(self):
  250.         cs = self.circles
  251.         min_d = 2 * RADIUS
  252.         for i in range(len(cs)):
  253.             a = cs[i]
  254.             for j in range(i + 1, len(cs)):
  255.                 b = cs[j]
  256.                 dx, dy = b.x - a.x, b.y - a.y
  257.                 d2 = dx * dx + dy * dy
  258.                 if d2 >= min_d * min_d or d2 == 0:
  259.                     continue
  260.                 d = math.sqrt(d2)
  261.                 nx, ny = dx / d, dy / d
  262.                 push = (min_d - d) / 2
  263.                 a.x -= nx * push
  264.                 a.y -= ny * push
  265.                 b.x += nx * push
  266.                 b.y += ny * push
  267.                 rel = (b.vx - a.vx) * nx + (b.vy - a.vy) * ny
  268.                 if rel < 0:
  269.                     a.vx += rel * nx
  270.                     a.vy += rel * ny
  271.                     b.vx -= rel * nx
  272.                     b.vy -= rel * ny
  273.  
  274.  
  275. # ---------------------------------------------------------------- tkinter view
  276. def main():
  277.     import tkinter as tk
  278.  
  279.     root = tk.Tk()
  280.     root.title("Ray-firing circles")
  281.     canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg=BG, highlightthickness=0)
  282.     canvas.pack()
  283.  
  284.     sim = Sim()
  285.  
  286.     # sliders
  287.     panel = tk.Frame(root, bg=BG)
  288.     panel.pack(fill="x")
  289.     slider_style = dict(orient="horizontal", length=380, bg=BG, fg=TEXT_COLOR,
  290.                         troughcolor="#1e2232", highlightthickness=0,
  291.                         font=("Courier", 10), takefocus=0)
  292.  
  293.     rate_var = tk.DoubleVar(value=sim.max_rate)
  294.     tk.Scale(panel, label="firing rate (max shots/s per circle)", variable=rate_var,
  295.              from_=BASE_RATE, to=30.0, resolution=0.1,
  296.              command=lambda v: setattr(sim, "max_rate", float(v)),
  297.              **slider_style).pack(side="left", padx=12, pady=6)
  298.  
  299.     friction_var = tk.DoubleVar(value=sim.damping)
  300.     tk.Scale(panel, label="friction (velocity decay per s)", variable=friction_var,
  301.              from_=0.0, to=10.0, resolution=0.1,
  302.              command=lambda v: setattr(sim, "damping", float(v)),
  303.              **slider_style).pack(side="left", padx=12, pady=6)
  304.     state = {"paused": False}
  305.     ovals = []
  306.  
  307.     def build_ovals():
  308.         for o in ovals:
  309.             canvas.delete(o)
  310.         ovals.clear()
  311.         for _ in sim.circles:
  312.             ovals.append(canvas.create_oval(0, 0, 0, 0, fill=CIRCLE_COLOR, outline=""))
  313.  
  314.     build_ovals()
  315.  
  316.     hud = canvas.create_text(10, 10, anchor="nw", fill=TEXT_COLOR, font=("Courier", 11))
  317.     x = 10
  318.     for label, col in (("random (up front)", COLOR_UPFRONT),
  319.                        ("random (weighted draw)", COLOR_WEIGHTED_RANDOM),
  320.                        ("aimed", COLOR_AIMED)):
  321.         canvas.create_line(x, HEIGHT - 14, x + 22, HEIGHT - 14, fill=col, width=3)
  322.         t = canvas.create_text(x + 28, HEIGHT - 14, anchor="w", text=label,
  323.                                fill=TEXT_COLOR, font=("Courier", 10))
  324.         x = canvas.bbox(t)[2] + 20
  325.  
  326.     def on_key(e):
  327.         k = e.keysym.lower()
  328.         if k == "space":
  329.             state["paused"] = not state["paused"]
  330.         elif k == "r":
  331.             sim.reset()
  332.             build_ovals()
  333.             canvas.tag_raise(hud)
  334.         elif k == "c":
  335.             sim.collisions = not sim.collisions
  336.         elif k == "escape":
  337.             root.destroy()
  338.  
  339.     root.bind("<Key>", on_key)
  340.  
  341.     dt = 1.0 / FPS
  342.  
  343.     def tick():
  344.         if not state["paused"]:
  345.             sim.step(dt)
  346.         canvas.delete("ray")
  347.         for ray in sim.rays:
  348.             canvas.create_line(ray.x - ray.dx * RAY_STREAK, ray.y - ray.dy * RAY_STREAK,
  349.                                ray.x, ray.y, fill=RAY_COLORS[ray.kind], width=2, tags="ray")
  350.         for o, c in zip(ovals, sim.circles):
  351.             canvas.coords(o, c.x - RADIUS, c.y - RADIUS, c.x + RADIUS, c.y + RADIUS)
  352.         s = sim.shots
  353.         canvas.itemconfigure(hud, text=(
  354.             f"shots: {s[UPFRONT]} up-front random, {s[WEIGHTED_RANDOM]} weighted random, "
  355.             f"{s[AIMED]} aimed   hits: {sim.hits}\n"
  356.             f"collisions {'on' if sim.collisions else 'off'} (C)   R reset   "
  357.             f"Space {'resume' if state['paused'] else 'pause'}   Esc quit"))
  358.         root.after(int(1000 / FPS), tick)
  359.  
  360.     tick()
  361.     root.mainloop()
  362.  
  363.  
  364. if __name__ == "__main__":
  365.     main()
Advertisement
Add Comment
Please, Sign In to add comment