Files
2025-04-13 16:26:57 +02:00

54 lines
1.4 KiB
Python

from fastapi import FastAPI
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
import random, threading, time
app = FastAPI()
# Serve static and HTML files
app.mount("/static", StaticFiles(directory="static"), name="static")
# Initialize game grid
GRID = [random.randint(0,9) for _ in range(9)]
LOCK = threading.Lock()
# Track start time to gradually reduce the interval
START_TIME = time.time()
# Get interval from 3s down to 0.5s over 120s
# Then remain at 0.5s thereafter
def get_interval():
elapsed = time.time() - START_TIME
# linear from t=0 => 3s, t=120 => 0.5s
# interval(t) = -1/48 * t + 3, clamped to min 0.5
return max(0.5, -elapsed / 48 + 3)
# Randomly change one number every get_interval() seconds
def change_number():
global GRID
while True:
print("Changing a number in flipnum...")
with LOCK:
idx = random.randint(0, 8)
old_num = GRID[idx]
new_num = random.choice([x for x in range(10) if x != old_num])
GRID[idx] = new_num
time.sleep(get_interval())
@app.on_event("startup")
def startup_event():
threading.Thread(target=change_number, daemon=True).start()
@app.get("/", response_class=HTMLResponse)
def index():
with open("static/index.html") as f:
return f.read()
@app.get("/get_grid")
def get_grid():
with LOCK:
return JSONResponse(GRID)