Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Ray-firing circles (standard library only: tkinter for drawing)
- Rules
- -----
- Firing rate
- Each circle fires as a Poisson process whose rate depends on how close its
- nearest neighbour is:
- rate = BASE_RATE + (MAX_RATE - BASE_RATE) * 2 ** (-d_nearest / RATE_HALF_DIST)
- So an isolated circle fires about BASE_RATE times/s, and one with a neighbour
- right on top of it fires close to MAX_RATE times/s.
- Choosing a direction
- 1. With probability UPFRONT_RANDOM, fire in a uniformly random direction.
- 2. Otherwise pick one option, weighted:
- - every other circle j has weight 2 ** (-d_j / TARGET_HALF_DIST)
- - "random direction" has weight 1, as if it were a neighbour at
- distance 0 (sitting right on top of the firer).
- Picking a circle fires straight at it; picking "random" fires in a
- uniformly random direction.
- Example (half-distance = 1 unit): 8 neighbours at 3 units each have weight
- 1/8, so after step 1 each gets 1/16 and random gets 1/2.
- Hits
- A circle hit by a ray gets a velocity kick of PULL_IMPULSE toward the
- circle that fired it.
- Ray colours
- blue random, decided up front (step 1)
- violet random, chosen in the weighted draw (step 2)
- orange aimed at a circle
- Sliders
- firing rate MAX_RATE: shots/s a circle fires when a neighbour is right on top of it
- friction DAMPING: velocity shrinks by a factor exp(-friction) every second
- Controls
- Space pause/resume R reset C toggle circle-circle collisions
- Esc quit
- """
- import math
- import random
- # ---------------------------------------------------------------- settings
- WIDTH, HEIGHT = 1000, 700
- FPS = 60
- NUM_CIRCLES = 60
- RADIUS = 5
- # firing rate (shots per second per circle)
- BASE_RATE = 0.4
- MAX_RATE = 8.0
- RATE_HALF_DIST = 25.0 # px: rate boost halves for every this-many px to the nearest neighbour
- # targeting
- UPFRONT_RANDOM = 0.10
- TARGET_HALF_DIST = 25.0 # px: a neighbour's weight halves for every this-many px of distance
- # rays
- RAY_SPEED = 1800.0 # px / s
- RAY_STREAK = 30.0 # drawn length, px
- # motion
- PULL_IMPULSE = 18.0 # px/s added toward the firer on a hit
- DAMPING = 2.0 # v *= exp(-DAMPING * dt)
- MAX_SPEED = 400.0
- START_SPEED = 20.0
- COLLISIONS = False # circle-circle collisions (toggle with C)
- BG = "#0c0e16"
- CIRCLE_COLOR = "#c8cddc"
- COLOR_UPFRONT = "#5ac8ff"
- COLOR_WEIGHTED_RANDOM = "#b48cff"
- COLOR_AIMED = "#ff963c"
- TEXT_COLOR = "#969bab"
- UPFRONT, WEIGHTED_RANDOM, AIMED = 0, 1, 2
- RAY_COLORS = {UPFRONT: COLOR_UPFRONT,
- WEIGHTED_RANDOM: COLOR_WEIGHTED_RANDOM,
- AIMED: COLOR_AIMED}
- # ---------------------------------------------------------------- model
- class Circle:
- __slots__ = ("x", "y", "vx", "vy")
- def __init__(self, x, y):
- self.x, self.y = x, y
- a = random.uniform(0, math.tau)
- s = random.uniform(0, START_SPEED)
- self.vx, self.vy = math.cos(a) * s, math.sin(a) * s
- class Ray:
- __slots__ = ("owner", "x", "y", "dx", "dy", "kind", "alive")
- def __init__(self, owner, x, y, dx, dy, kind):
- self.owner = owner
- self.x, self.y = x, y
- self.dx, self.dy = dx, dy
- self.kind = kind
- self.alive = True
- def segment_hit_t(x0, y0, x1, y1, cx, cy, r):
- """Smallest t in [0,1] where segment (x0,y0)->(x1,y1) touches the circle, else None."""
- fx, fy = x0 - cx, y0 - cy
- dx, dy = x1 - x0, y1 - y0
- a = dx * dx + dy * dy
- c = fx * fx + fy * fy - r * r
- if c <= 0:
- return 0.0
- if a == 0:
- return None
- b = 2 * (fx * dx + fy * dy)
- disc = b * b - 4 * a * c
- if disc < 0:
- return None
- t = (-b - math.sqrt(disc)) / (2 * a)
- return t if 0.0 <= t <= 1.0 else None
- class Sim:
- def __init__(self):
- self.collisions = COLLISIONS
- self.max_rate = MAX_RATE # adjustable at runtime ("firing rate" slider)
- self.damping = DAMPING # adjustable at runtime ("friction" slider)
- self.reset()
- def reset(self):
- self.circles = [Circle(random.uniform(RADIUS, WIDTH - RADIUS),
- random.uniform(RADIUS, HEIGHT - RADIUS))
- for _ in range(NUM_CIRCLES)]
- self.rays = []
- self.shots = {UPFRONT: 0, WEIGHTED_RANDOM: 0, AIMED: 0}
- self.hits = 0
- # -- firing ------------------------------------------------------
- def choose_direction(self, i, dists):
- """dists[j] = distance from circle i to circle j. Returns (dx, dy, kind)."""
- if random.random() < UPFRONT_RANDOM:
- a = random.uniform(0, math.tau)
- return math.cos(a), math.sin(a), UPFRONT
- # weight 1 for "random" (a phantom neighbour at distance 0)
- total = 1.0
- weights = []
- for j, d in enumerate(dists):
- w = 0.0 if j == i else 2.0 ** (-d / TARGET_HALF_DIST)
- weights.append(w)
- total += w
- pick = random.random() * total
- if pick >= 1.0:
- pick -= 1.0
- for j, w in enumerate(weights):
- if pick < w:
- me, other = self.circles[i], self.circles[j]
- tx, ty = other.x - me.x, other.y - me.y
- d = math.hypot(tx, ty)
- if d > 1e-9:
- return tx / d, ty / d, AIMED
- break # exactly coincident: no defined direction, fall through
- pick -= w
- a = random.uniform(0, math.tau)
- return math.cos(a), math.sin(a), WEIGHTED_RANDOM
- def fire(self, i, dists):
- c = self.circles[i]
- dx, dy, kind = self.choose_direction(i, dists)
- sx, sy = c.x + dx * (RADIUS + 0.5), c.y + dy * (RADIUS + 0.5)
- self.rays.append(Ray(i, sx, sy, dx, dy, kind))
- self.shots[kind] += 1
- # -- step --------------------------------------------------------
- def step(self, dt):
- cs = self.circles
- n = len(cs)
- # pairwise distances (needed for firing rate and targeting)
- dist = [[0.0] * n for _ in range(n)]
- for i in range(n):
- a = cs[i]
- row = dist[i]
- for j in range(i + 1, n):
- b = cs[j]
- d = math.hypot(b.x - a.x, b.y - a.y)
- row[j] = d
- dist[j][i] = d
- for i in range(n):
- nearest = min(d for j, d in enumerate(dist[i]) if j != i) if n > 1 else math.inf
- rate = BASE_RATE + max(0.0, self.max_rate - BASE_RATE) * 2.0 ** (-nearest / RATE_HALF_DIST)
- if random.random() < 1.0 - math.exp(-rate * dt):
- self.fire(i, dist[i])
- # move rays, swept collision test
- for ray in self.rays:
- step = RAY_SPEED * dt
- nx, ny = ray.x + ray.dx * step, ray.y + ray.dy * step
- best_t, best_j = None, None
- for j, c in enumerate(cs):
- if j == ray.owner:
- continue
- t = segment_hit_t(ray.x, ray.y, nx, ny, c.x, c.y, RADIUS)
- if t is not None and (best_t is None or t < best_t):
- best_t, best_j = t, j
- if best_j is not None:
- target, firer = cs[best_j], cs[ray.owner]
- px, py = firer.x - target.x, firer.y - target.y
- d = math.hypot(px, py)
- if d > 1e-9:
- target.vx += px / d * PULL_IMPULSE
- target.vy += py / d * PULL_IMPULSE
- ray.alive = False
- self.hits += 1
- continue
- ray.x, ray.y = nx, ny
- if not (-RAY_STREAK <= nx <= WIDTH + RAY_STREAK and
- -RAY_STREAK <= ny <= HEIGHT + RAY_STREAK):
- ray.alive = False
- self.rays = [r for r in self.rays if r.alive]
- # move circles
- decay = math.exp(-self.damping * dt)
- for c in cs:
- c.vx *= decay
- c.vy *= decay
- sp = math.hypot(c.vx, c.vy)
- if sp > MAX_SPEED:
- c.vx *= MAX_SPEED / sp
- c.vy *= MAX_SPEED / sp
- c.x += c.vx * dt
- c.y += c.vy * dt
- if c.x < RADIUS:
- c.x, c.vx = RADIUS, abs(c.vx)
- elif c.x > WIDTH - RADIUS:
- c.x, c.vx = WIDTH - RADIUS, -abs(c.vx)
- if c.y < RADIUS:
- c.y, c.vy = RADIUS, abs(c.vy)
- elif c.y > HEIGHT - RADIUS:
- c.y, c.vy = HEIGHT - RADIUS, -abs(c.vy)
- if self.collisions:
- self.resolve_collisions()
- def resolve_collisions(self):
- cs = self.circles
- min_d = 2 * RADIUS
- for i in range(len(cs)):
- a = cs[i]
- for j in range(i + 1, len(cs)):
- b = cs[j]
- dx, dy = b.x - a.x, b.y - a.y
- d2 = dx * dx + dy * dy
- if d2 >= min_d * min_d or d2 == 0:
- continue
- d = math.sqrt(d2)
- nx, ny = dx / d, dy / d
- push = (min_d - d) / 2
- a.x -= nx * push
- a.y -= ny * push
- b.x += nx * push
- b.y += ny * push
- rel = (b.vx - a.vx) * nx + (b.vy - a.vy) * ny
- if rel < 0:
- a.vx += rel * nx
- a.vy += rel * ny
- b.vx -= rel * nx
- b.vy -= rel * ny
- # ---------------------------------------------------------------- tkinter view
- def main():
- import tkinter as tk
- root = tk.Tk()
- root.title("Ray-firing circles")
- canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg=BG, highlightthickness=0)
- canvas.pack()
- sim = Sim()
- # sliders
- panel = tk.Frame(root, bg=BG)
- panel.pack(fill="x")
- slider_style = dict(orient="horizontal", length=380, bg=BG, fg=TEXT_COLOR,
- troughcolor="#1e2232", highlightthickness=0,
- font=("Courier", 10), takefocus=0)
- rate_var = tk.DoubleVar(value=sim.max_rate)
- tk.Scale(panel, label="firing rate (max shots/s per circle)", variable=rate_var,
- from_=BASE_RATE, to=30.0, resolution=0.1,
- command=lambda v: setattr(sim, "max_rate", float(v)),
- **slider_style).pack(side="left", padx=12, pady=6)
- friction_var = tk.DoubleVar(value=sim.damping)
- tk.Scale(panel, label="friction (velocity decay per s)", variable=friction_var,
- from_=0.0, to=10.0, resolution=0.1,
- command=lambda v: setattr(sim, "damping", float(v)),
- **slider_style).pack(side="left", padx=12, pady=6)
- state = {"paused": False}
- ovals = []
- def build_ovals():
- for o in ovals:
- canvas.delete(o)
- ovals.clear()
- for _ in sim.circles:
- ovals.append(canvas.create_oval(0, 0, 0, 0, fill=CIRCLE_COLOR, outline=""))
- build_ovals()
- hud = canvas.create_text(10, 10, anchor="nw", fill=TEXT_COLOR, font=("Courier", 11))
- x = 10
- for label, col in (("random (up front)", COLOR_UPFRONT),
- ("random (weighted draw)", COLOR_WEIGHTED_RANDOM),
- ("aimed", COLOR_AIMED)):
- canvas.create_line(x, HEIGHT - 14, x + 22, HEIGHT - 14, fill=col, width=3)
- t = canvas.create_text(x + 28, HEIGHT - 14, anchor="w", text=label,
- fill=TEXT_COLOR, font=("Courier", 10))
- x = canvas.bbox(t)[2] + 20
- def on_key(e):
- k = e.keysym.lower()
- if k == "space":
- state["paused"] = not state["paused"]
- elif k == "r":
- sim.reset()
- build_ovals()
- canvas.tag_raise(hud)
- elif k == "c":
- sim.collisions = not sim.collisions
- elif k == "escape":
- root.destroy()
- root.bind("<Key>", on_key)
- dt = 1.0 / FPS
- def tick():
- if not state["paused"]:
- sim.step(dt)
- canvas.delete("ray")
- for ray in sim.rays:
- canvas.create_line(ray.x - ray.dx * RAY_STREAK, ray.y - ray.dy * RAY_STREAK,
- ray.x, ray.y, fill=RAY_COLORS[ray.kind], width=2, tags="ray")
- for o, c in zip(ovals, sim.circles):
- canvas.coords(o, c.x - RADIUS, c.y - RADIUS, c.x + RADIUS, c.y + RADIUS)
- s = sim.shots
- canvas.itemconfigure(hud, text=(
- f"shots: {s[UPFRONT]} up-front random, {s[WEIGHTED_RANDOM]} weighted random, "
- f"{s[AIMED]} aimed hits: {sim.hits}\n"
- f"collisions {'on' if sim.collisions else 'off'} (C) R reset "
- f"Space {'resume' if state['paused'] else 'pause'} Esc quit"))
- root.after(int(1000 / FPS), tick)
- tick()
- root.mainloop()
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment