Files
devplacepy/devplacepy/services/opinionwar/rules.py
T
blindxfishandClaude Fable 5 80956ce0f4 Add Opinion Wars: week-long two-faction battles attached to posts
A new post attachment type beside polls: the composer gains a Start
Opinion War builder (same disabled-inputs opt-in as the poll builder)
that names exactly two factions; the battle runs for exactly 7 days
from post creation. Members join a side, may defect at any time
(damage already dealt stays with the faction it was dealt to), and
fight once per 24 hours per battle. A fight spends 25 Code Farm coins
and deals deterministic level-weighted damage: 100 + 10 * min(level,
20) HP, so a newcomer deals 110 and a veteran caps at 300 - no
randomness anywhere.

The battle renders on the post card as a CSS pixel-art battlefield
(box-shadow sprites: castles, faction flags, marching soldiers, a
flickering campfire; steps() animation, disabled under reduced motion)
with live HP bars, a countdown, the viewer's faction strip, top
contributors and an event ticker. Live frames ride pub/sub on
public.battle.{uid} via a relay on the service-lock owner, with the
durable opinion_war_events trail (per-war atomic seq) as the source of
truth and a 15s incremental poller as fallback. /battles lists battles
with active/ended/mine filters, search and pagination.

Every mutation is a conditional UPDATE via conditional_update_row: the
fight sequence claims the cooldown first, then spends coins, then lands
the damage, compensating earlier steps on any later refusal so a crash
costs a turn, never coins. Resolution is lazy on read (no cron):
an exactly-once CAS computes the winner in the statement, awards XP
(participation, winner bonus, top damage dealer bonus; draws pay
participation only), emits the result event and notifies fighters. The
OpinionWarService backstop resolves unviewed wars and sends
fight-ready notifications, exactly-once via a marker CAS.

Fan-out: battle notification type, four badges, audit keys
(battle.create/join/switch/fight/resolve), Devii actions (join/fight
confirm-gated), API docs group, docs prose page, sitemap and topnav
entries, REPORTABLE_TARGETS registration, post-delete cascades,
README and nested CLAUDE.md documentation.

Verified with the four-layer procedure: property checks over the full
damage domain, 1200-step stateful fuzz (hp-sum invariant, coins never
negative, resolved totals frozen), and real 8-process races proving
exactly-once semantics for concurrent fights, double-spends across two
wars, resolution XP and double-joins. Persisted tests in
tests/unit/services/opinionwar, tests/api/battles, tests/e2e/battles
and tests/api/posts/create.py.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 23:30:02 +02:00

112 lines
2.8 KiB
Python

# retoor <retoor@molodetz.nl>
from __future__ import annotations
from datetime import datetime, timedelta, timezone
WAR_DURATION_DAYS = 7
FIGHT_COST_COINS = 25
FIGHT_COOLDOWN_HOURS = 24
BASE_DAMAGE = 100
LEVEL_DAMAGE_STEP = 10
LEVEL_DAMAGE_CAP = 20
FACTION_NAME_MAX = 30
TOP_CONTRIBUTORS = 3
EVENT_TICKER_LIMIT = 5
EVENT_LIMIT_DEFAULT = 500
EVENT_KINDS = ("join", "switch", "fight", "lead_change", "result")
def _parse(value: str | None) -> datetime | None:
if not value:
return None
try:
parsed = datetime.fromisoformat(value)
except (TypeError, ValueError):
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed
def _now(now: datetime | None = None) -> datetime:
return now or datetime.now(timezone.utc)
def damage_for(level) -> int:
try:
value = int(level or 1)
except (TypeError, ValueError):
value = 1
return BASE_DAMAGE + LEVEL_DAMAGE_STEP * min(max(value, 1), LEVEL_DAMAGE_CAP)
def ends_at_for(created_at: str) -> str:
start = _parse(created_at) or _now()
return (start + timedelta(days=WAR_DURATION_DAYS)).isoformat()
def is_ended(ends_at: str, now: datetime | None = None) -> bool:
ends = _parse(ends_at)
if not ends:
return False
return _now(now) >= ends
def cooldown_cutoff(now: datetime | None = None) -> str:
return (_now(now) - timedelta(hours=FIGHT_COOLDOWN_HOURS)).isoformat()
def cooldown_ready_at(last_fight_at: str) -> str:
last = _parse(last_fight_at)
if not last:
return ""
return (last + timedelta(hours=FIGHT_COOLDOWN_HOURS)).isoformat()
def can_fight_at(last_fight_at: str, now: datetime | None = None) -> bool:
ready = _parse(cooldown_ready_at(last_fight_at))
if not ready:
return True
return _now(now) >= ready
def leader_of(hp_a: int, hp_b: int) -> str:
if hp_a > hp_b:
return "a"
if hp_b > hp_a:
return "b"
return ""
def winner_of(hp_a: int, hp_b: int) -> str:
return leader_of(hp_a, hp_b) or "draw"
def pct_split(hp_a: int, hp_b: int) -> tuple[int, int]:
left = max(0, int(hp_a or 0))
right = max(0, int(hp_b or 0))
total = left + right
if not total:
return 50, 50
pct_a = round(left * 100 / total)
return pct_a, 100 - pct_a
def ends_in_label(ends_at: str, now: datetime | None = None) -> str:
ends = _parse(ends_at)
if not ends:
return ""
remaining = (ends - _now(now)).total_seconds()
if remaining <= 0:
return ""
minutes = int(remaining // 60)
days, minutes = divmod(minutes, 1440)
hours, minutes = divmod(minutes, 60)
if days:
return f"{days}d {hours}h {minutes}m"
if hours:
return f"{hours}h {minutes}m"
return f"{max(minutes, 1)}m"