🎮ArcadeLab

猫武士 · 演替兴衰(完整版)

by EpicCoder88
1823 lines65.9 KB
▶ Play
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>猫武士 · 演替兴衰(完整版)</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: system-ui; }
        body {
            background: #111;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 10px;
            overflow: hidden;
            touch-action: none;
            user-select: none;
        }
        canvas {
            border: 2px solid #444;
            border-radius: 6px;
            touch-action: none;
            max-width: 100%;
            background: #477c42;
            display: block;
        }
        .panel {
            margin-top: 8px;
            width: 900px;
            max-width: 100%;
            background: #1a1a1a;
            border: 2px solid #444;
            border-radius: 6px;
            padding: 10px 14px;
            color: #ddd;
            font-size: 14px;
            line-height: 1.6;
        }
        .panel strong { color: #fff; }
        #detailPanel {
            margin-top: 6px;
            border-top: 1px solid #444;
            padding-top: 6px;
            font-size: 13px;
            color: #aaa;
            min-height: 1.5em;
        }
        .speed-control {
            margin-top: 6px;
            display: flex;
            gap: 8px;
            align-items: center;
            flex-wrap: wrap;
        }
        .speed-control button {
            background: #333;
            color: #ddd;
            border: 1px solid #555;
            border-radius: 4px;
            padding: 4px 12px;
            cursor: pointer;
            font-size: 14px;
        }
        .speed-control button.active {
            background: #5a7a5a;
            border-color: #8aa88a;
        }
        .reset-btn {
            background: #5a3a3a;
            color: #ddd;
            border: 1px solid #8a5a5a;
            border-radius: 4px;
            padding: 4px 12px;
            cursor: pointer;
            font-size: 14px;
            margin-left: 8px;
        }
        .info-text {
            font-size: 12px;
            color: #888;
            margin-top: 4px;
        }
        #timeDisplay {
            color: #ffd700;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <canvas id="worldCanvas" width="900" height="600"></canvas>

    <div class="panel">
        <div><strong>生态实时面板</strong></div>
        <div id="populationPanel">猎物:0 / 草:0 / 成年猫:0 / 幼猫:0 / 跟随:无</div>
        <div id="detailPanel">点击一只猫查看详情</div>
        <div class="speed-control">
            <span style="color:#888; font-size:13px;">速度:</span>
            <button id="speed1x" class="active" onclick="setSpeed(1)">1×</button>
            <button id="speed2x" onclick="setSpeed(2)">2×</button>
            <button id="speed5x" onclick="setSpeed(5)">5×</button>
            <button class="reset-btn" onclick="resetWorld()">重置</button>
            <span id="timeDisplay" style="margin-left:10px;">☀️ 白天</span>
        </div>
        <div class="info-text">
            点击猫跟随|拖拽平移|双指/滚轮缩放|深绿三角=草|黑点=猎物|橘色=猫|粉色环=可繁殖|红圈=饥饿|🌙夜晚变暗|🌳灌木(半透明,挡视线)|🌿荆棘(实心有碰撞)
        </div>
    </div>

<script>
window.onload = function() {

const canvas = document.getElementById("worldCanvas");
const ctx = canvas.getContext("2d");
const populationPanel = document.getElementById("populationPanel");
const detailPanel = document.getElementById("detailPanel");
const timeDisplay = document.getElementById("timeDisplay");

// ========== 名字库 ==========
const PREFIXES = [
    "虎", "鹰", "鸦", "松鸦", "香薇", "冬青", "蕨", "玫瑰", "火", "云", "雾", "风",
    "灰", "蓝", "斑", "长", "短", "亮", "暗", "雨", "雪", "霜", "露", "溪", "河",
    "湖", "星", "月", "日", "影", "光", "叶", "花", "石", "岩", "荆棘", "芦苇",
    "柳", "橡", "枫", "桦", "松", "杉", "白", "黑", "红", "金", "银", "铜"
];
const SUFFIXES = [
    "尾", "羽", "花", "毛", "爪", "足", "心", "风", "叶", "霜", "云", "星",
    "光", "月", "溪", "河", "湖", "石", "岩", "棘", "苇", "柳", "橡", "枫",
    "桦", "松", "杉", "飞", "跃", "奔", "步", "啸", "嚎", "眼", "耳", "鼻",
    "须", "掌", "腿", "腹", "背", "额", "面", "斑", "纹", "环"
];

// ========== 配置 ==========
const GRID_SIZE = 60;
const GRID_ALPHA = 0.35;
const DASH_PATTERN = [8,6];
const GRID_COLOR = "#ffffff";
const GRASS_COLOR = "#477c42";

const TREE_COLOR = "#6b4423";
const TREE_RADIUS = 22;
const TREE_COLLIDE_RADIUS = 28;
const TREE_BLOCK_RAY_RADIUS = 26;
const TREE_MIN_DISTANCE = 110;
const TREE_TOTAL_COUNT = 18;

const HERB_COLOR = "#1c4d19";
const HERB_SIZE = 10;
const HERB_MAX_COUNT = 80;
const HERB_MIN_SPACE = 35;
const HERB_RESPAWN_INTERVAL = 160;

const PREY_RADIUS = 8;
const PREY_COUNT = 28;
const PREY_MAX_COUNT = 70;
const PREY_SPEED = 1.1;
const PREY_FLEE_SPEED = 3.0;
const PREY_VIEW_RANGE = 170;
const PREY_VIEW_ANGLE = Math.PI / 3;
const PREY_FEED_RANGE = 16;
const BREED_DISTANCE = 35;
const FEED_REQUIRE = 3;
const BABY_COUNT = 4;
const MAX_HUNGER_TIME = 2500;

const CAT_COLOR = "#f2a65a";
const CAT_RADIUS = 14;
const CAT_SPEED = 1.4;
const CAT_VIEW_RANGE = 220;
const CAT_VIEW_ANGLE = Math.PI / 3;
const CAT_HUNT_RANGE = 25;
const REWARD_CATCH = 10;
const PENALTY_ESCAPE = -6;
const CAT_BREED_REQUIRE = 4;
const CAT_BREED_DISTANCE = 40;
const CAT_BREED_COOLDOWN = 800;
const CAT_LITTER_SIZE = 2;
const CAT_GROW_TIME = 1800;
const CAT_HUNGER_MAX = 3000;
const CAT_HUNGER_STATE = 600;
const CAT_FULL_THRESHOLD = 2000;
const MAX_CATS = 120;

// 昼夜时长(帧数)
const DAY_LENGTH = 2400;
const NIGHT_LENGTH = 1800;

// 灌木和荆棘
const BUSH_COUNT = 40;
const BUSH_RADIUS = 30;
const THORN_COUNT = 25;
const THORN_RADIUS = 22;

// 窝相关
const NEST_CHECK_RADIUS = 80;
const NEST_PREFER_RADIUS = 120; // 倾向在已有窝附近做窝

const MALE_SYMBOL = "♂";
const FEMALE_SYMBOL = "♀";

const WORLD_BOUND = {
    left: -300,
    top: -200,
    right: 1500,
    bottom: 1000
};

// ======== 相机 ========
let offsetX = 0, offsetY = 0, scale = 1.0;
const MIN_SCALE = 0.3, MAX_SCALE = 2.5;
let isDragging = false;
let dragStartX = 0, dragStartY = 0;
let startOffsetX = 0, startOffsetY = 0;
let lastTouchDist = 0;
let followedCat = null;

let pointerDownX = 0, pointerDownY = 0;
let pointerDownTime = 0;
let isClick = false;

let speedMultiplier = 1;

// ========== 实体容器 ==========
let trees = [], herbs = [], preys = [], cats = [];
let bushes = [], thorns = [], nests = [];
let herbRespawnTimer = 0;
let floatingTexts = [];

// ========== 昼夜状态 ==========
let isDay = true;
let dayTimer = 0;
let nightTimer = 0;

// ========== 工具 ==========
function isPointInWorld(x, y) {
    return x >= WORLD_BOUND.left && x <= WORLD_BOUND.right &&
           y >= WORLD_BOUND.top && y <= WORLD_BOUND.bottom;
}

function screenToWorld(screenX, screenY) {
    return { x: (screenX - offsetX) / scale, y: (screenY - offsetY) / scale };
}

function getCanvasCoords(clientX, clientY) {
    const rect = canvas.getBoundingClientRect();
    return {
        x: (clientX - rect.left) * (canvas.width / rect.width),
        y: (clientY - rect.top) * (canvas.height / rect.height)
    };
}

function getPixelRatio() {
    const rect = canvas.getBoundingClientRect();
    return canvas.width / rect.width;
}

// 点是否在圆内
function pointInCircle(px, py, cx, cy, r) {
    return Math.hypot(px - cx, py - cy) <= r;
}

// 线段与圆相交检测(用于视线阻挡)
function lineIntersectsCircle(x1, y1, x2, y2, cx, cy, r) {
    const dx = x2 - x1;
    const dy = y2 - y1;
    const fx = x1 - cx;
    const fy = y1 - cy;
    const a = dx * dx + dy * dy;
    const b = 2 * (fx * dx + fy * dy);
    const c = fx * fx + fy * fy - r * r;
    let discriminant = b * b - 4 * a * c;
    if (discriminant < 0) return false;
    discriminant = Math.sqrt(discriminant);
    const t1 = (-b - discriminant) / (2 * a);
    const t2 = (-b + discriminant) / (2 * a);
    if (t1 >= 0 && t1 <= 1) return true;
    if (t2 >= 0 && t2 <= 1) return true;
    return false;
}

// ========== 碰撞检测(树和荆棘) ==========
function checkCollision(x, y, radius) {
    // 树木
    for (const tree of trees) {
        if (Math.hypot(x - tree.x, y - tree.y) < TREE_COLLIDE_RADIUS + radius) return true;
    }
    // 荆棘
    for (const thorn of thorns) {
        if (Math.hypot(x - thorn.x, y - thorn.y) < THORN_RADIUS + radius) return true;
    }
    return false;
}

// ========== 视线检测(树木、灌木) ==========
function isLineBlocked(x1, y1, x2, y2) {
    // 树木阻挡
    for (const tree of trees) {
        const tx = tree.x, ty = tree.y;
        const A = x1 - tx, B = y1 - ty;
        const C = x2 - x1, D = y2 - y1;
        const dot = A * C + B * D;
        if (dot <= 0) {
            if (Math.hypot(A, B) < TREE_BLOCK_RAY_RADIUS) return true;
            continue;
        }
        const lenSq = C * C + D * D;
        if (dot >= lenSq) {
            if (Math.hypot(x2 - tx, y2 - ty) < TREE_BLOCK_RAY_RADIUS) return true;
            continue;
        }
        const t = dot / lenSq;
        const nearX = x1 + t * C, nearY = y1 + t * D;
        if (Math.hypot(nearX - tx, nearY - ty) < TREE_BLOCK_RAY_RADIUS) return true;
    }

    // 灌木阻挡(如果起点不在灌木内部,则阻挡穿过灌木的视线)
    for (const bush of bushes) {
        // 如果起点在灌木内部,则不阻挡该灌木
        if (pointInCircle(x1, y1, bush.x, bush.y, BUSH_RADIUS)) continue;
        // 如果终点在灌木内部,视为阻挡(外部看内部不可见)
        if (pointInCircle(x2, y2, bush.x, bush.y, BUSH_RADIUS)) return true;
        // 线段与灌木圆相交
        if (lineIntersectsCircle(x1, y1, x2, y2, bush.x, bush.y, BUSH_RADIUS)) {
            return true;
        }
    }
    return false;
}

// ========== 安全移动(含碰撞) ==========
function safeMove(entity, moveX, moveY, radius) {
    let newX = entity.x + moveX;
    let newY = entity.y + moveY;

    const left = WORLD_BOUND.left + radius;
    const right = WORLD_BOUND.right - radius;
    const top = WORLD_BOUND.top + radius;
    const bottom = WORLD_BOUND.bottom - radius;

    let canX = (newX >= left && newX <= right);
    let canY = (newY >= top && newY <= bottom);

    let finalX = entity.x, finalY = entity.y;

    if (canX && canY) {
        finalX = newX; finalY = newY;
    } else if (canX && !canY) {
        finalX = newX; finalY = entity.y;
    } else if (!canX && canY) {
        finalX = entity.x; finalY = newY;
    } else {
        entity.stuckTimer = (entity.stuckTimer || 0) + 1;
        if (entity.stuckTimer > 25) {
            entity.x -= Math.cos(entity.angle) * 18;
            entity.y -= Math.sin(entity.angle) * 18;
            entity.angle += (Math.random() > 0.5 ? 1 : -1) * (Math.PI / 2 + Math.random() * Math.PI / 3);
            entity.stuckTimer = 0;
        } else {
            entity.angle += (Math.random() > 0.5 ? 0.4 : -0.4);
        }
        entity.x = Math.max(left, Math.min(right, entity.x));
        entity.y = Math.max(top, Math.min(bottom, entity.y));
        return;
    }

    if (checkCollision(finalX, finalY, radius)) {
        if (!checkCollision(finalX, entity.y, radius)) {
            finalY = entity.y;
        } else if (!checkCollision(entity.x, finalY, radius)) {
            finalX = entity.x;
        } else {
            entity.stuckTimer = (entity.stuckTimer || 0) + 1;
            if (entity.stuckTimer > 25) {
                entity.x -= Math.cos(entity.angle) * 18;
                entity.y -= Math.sin(entity.angle) * 18;
                entity.angle += (Math.random() > 0.5 ? 1 : -1) * (Math.PI / 2 + Math.random() * Math.PI / 3);
                entity.stuckTimer = 0;
            } else {
                entity.angle += (Math.random() > 0.5 ? 0.4 : -0.4);
            }
            entity.x = Math.max(left, Math.min(right, entity.x));
            entity.y = Math.max(top, Math.min(bottom, entity.y));
            return;
        }
    }

    entity.x = Math.max(left, Math.min(right, finalX));
    entity.y = Math.max(top, Math.min(bottom, finalY));
    entity.stuckTimer = 0;
}

// ========== 生成函数 ==========
function generateTrees() {
    trees = [];
    let tries = 0;
    while (trees.length < TREE_TOTAL_COUNT && tries < TREE_TOTAL_COUNT * 20) {
        tries++;
        const x = WORLD_BOUND.left + 50 + Math.random() * (WORLD_BOUND.right - WORLD_BOUND.left - 100);
        const y = WORLD_BOUND.top + 50 + Math.random() * (WORLD_BOUND.bottom - WORLD_BOUND.top - 100);
        let ok = true;
        for (const t of trees) if (Math.hypot(x - t.x, y - t.y) < TREE_MIN_DISTANCE) { ok = false; break; }
        if (ok) trees.push({ x, y });
    }
    if (trees.length === 0) {
        const fallback = [[0,0], [300,200], [-100,100], [500,-50], [200,400]];
        for (const [x,y] of fallback) trees.push({ x, y });
    }
}

function trySpawnHerb() {
    if (herbs.length >= HERB_MAX_COUNT) return false;
    for (let i = 0; i < 30; i++) {
        const x = WORLD_BOUND.left + 20 + Math.random() * (WORLD_BOUND.right - WORLD_BOUND.left - 40);
        const y = WORLD_BOUND.top + 20 + Math.random() * (WORLD_BOUND.bottom - WORLD_BOUND.top - 40);
        let ok = true;
        for (const t of trees) if (Math.hypot(x - t.x, y - t.y) < TREE_COLLIDE_RADIUS + 10) { ok = false; break; }
        if (!ok) continue;
        for (const h of herbs) if (Math.hypot(x - h.x, y - h.y) < HERB_MIN_SPACE) { ok = false; break; }
        if (ok) { herbs.push({ x, y }); return true; }
    }
    return false;
}

function generateHerbs() {
    herbs = [];
    let count = 0;
    while (count < HERB_MAX_COUNT && count < 120) {
        if (trySpawnHerb()) count++;
        else break;
    }
    if (herbs.length < 10) {
        for (let i = 0; i < 20; i++) {
            herbs.push({
                x: WORLD_BOUND.left + 30 + Math.random() * (WORLD_BOUND.right - WORLD_BOUND.left - 60),
                y: WORLD_BOUND.top + 30 + Math.random() * (WORLD_BOUND.bottom - WORLD_BOUND.top - 60)
            });
        }
    }
}

function createPrey(x, y) {
    return {
        x, y,
        angle: Math.random() * Math.PI * 2,
        wanderTimer: Math.random() * 100,
        targetHerb: null,
        targetMate: null,
        eatenHerbs: 0,
        breedCooldown: 0,
        hungerTimer: MAX_HUNGER_TIME,
        fleeTarget: null,
        stuckTimer: 0,
        isSleeping: false
    };
}

function generatePreys() {
    preys = [];
    let tries = 0;
    while (preys.length < PREY_COUNT && tries < PREY_COUNT * 30) {
        tries++;
        const x = WORLD_BOUND.left + 20 + Math.random() * (WORLD_BOUND.right - WORLD_BOUND.left - 40);
        const y = WORLD_BOUND.top + 20 + Math.random() * (WORLD_BOUND.bottom - WORLD_BOUND.top - 40);
        let ok = true;
        for (const t of trees) if (Math.hypot(x - t.x, y - t.y) < TREE_COLLIDE_RADIUS + PREY_RADIUS) { ok = false; break; }
        if (ok) { preys.push(createPrey(x, y)); }
    }
    if (preys.length < 5) {
        for (let i = 0; i < 10; i++) {
            preys.push(createPrey(
                WORLD_BOUND.left + 40 + Math.random() * (WORLD_BOUND.right - WORLD_BOUND.left - 80),
                WORLD_BOUND.top + 40 + Math.random() * (WORLD_BOUND.bottom - WORLD_BOUND.top - 80)
            ));
        }
    }
}

function generateBushes() {
    bushes = [];
    let tries = 0;
    while (bushes.length < BUSH_COUNT && tries < BUSH_COUNT * 30) {
        tries++;
        const x = WORLD_BOUND.left + 20 + Math.random() * (WORLD_BOUND.right - WORLD_BOUND.left - 40);
        const y = WORLD_BOUND.top + 20 + Math.random() * (WORLD_BOUND.bottom - WORLD_BOUND.top - 40);
        // 不与树木重叠
        let ok = true;
        for (const t of trees) if (Math.hypot(x - t.x, y - t.y) < TREE_COLLIDE_RADIUS + BUSH_RADIUS) { ok = false; break; }
        if (!ok) continue;
        // 灌木之间不重叠
        for (const b of bushes) if (Math.hypot(x - b.x, y - b.y) < BUSH_RADIUS * 1.8) { ok = false; break; }
        if (ok) bushes.push({ x, y, radius: BUSH_RADIUS });
    }
    // 保底
    if (bushes.length < 5) {
        for (let i = 0; i < 10; i++) {
            bushes.push({
                x: WORLD_BOUND.left + 30 + Math.random() * (WORLD_BOUND.right - WORLD_BOUND.left - 60),
                y: WORLD_BOUND.top + 30 + Math.random() * (WORLD_BOUND.bottom - WORLD_BOUND.top - 60),
                radius: BUSH_RADIUS
            });
        }
    }
}

function generateThorns() {
    thorns = [];
    let tries = 0;
    while (thorns.length < THORN_COUNT && tries < THORN_COUNT * 30) {
        tries++;
        const x = WORLD_BOUND.left + 20 + Math.random() * (WORLD_BOUND.right - WORLD_BOUND.left - 40);
        const y = WORLD_BOUND.top + 20 + Math.random() * (WORLD_BOUND.bottom - WORLD_BOUND.top - 40);
        let ok = true;
        for (const t of trees) if (Math.hypot(x - t.x, y - t.y) < TREE_COLLIDE_RADIUS + THORN_RADIUS) { ok = false; break; }
        if (!ok) continue;
        for (const th of thorns) if (Math.hypot(x - th.x, y - th.y) < THORN_RADIUS * 2) { ok = false; break; }
        if (ok) thorns.push({ x, y, radius: THORN_RADIUS });
    }
    if (thorns.length < 3) {
        for (let i = 0; i < 5; i++) {
            thorns.push({
                x: WORLD_BOUND.left + 30 + Math.random() * (WORLD_BOUND.right - WORLD_BOUND.left - 60),
                y: WORLD_BOUND.top + 30 + Math.random() * (WORLD_BOUND.bottom - WORLD_BOUND.top - 60),
                radius: THORN_RADIUS
            });
        }
    }
}

function randomGender() { return Math.random() < 0.5 ? "male" : "female"; }

function generateName() {
    const prefix = PREFIXES[Math.floor(Math.random() * PREFIXES.length)];
    const suffix = SUFFIXES[Math.floor(Math.random() * SUFFIXES.length)];
    return prefix + suffix;
}

function createCat(x, y, isAdult = true) {
    const name = generateName();
    return {
        x, y,
        angle: Math.random() * Math.PI * 2,
        wanderTimer: Math.random() * 120,
        targetPrey: null,
        targetMate: null,
        lastTarget: null,
        policyScore: 0,
        tryFlank: false,
        stuckTimer: 0,
        huntCount: 0,
        breedCooldown: 0,
        growTimer: isAdult ? CAT_GROW_TIME : 0,
        gender: randomGender(),
        hungerTimer: CAT_HUNGER_MAX,
        mate: null,
        parents: { father: null, mother: null },
        kittens: [],
        isLactating: false,
        milkSupply: 0,
        carryingPrey: null,
        targetMateLocation: null,
        name: name,
        helpingTarget: null,
        waitingForHelp: false,
        helpTargetPos: null,
        reputation: 0,
        isHelping: false,
        helpAttemptTimer: 0,
        // 新属性
        nest: null,        // 窝对象引用
        isSleeping: false,
        sleepPenalty: 0,   // 无窝睡眠惩罚累积
        buildNestCooldown: 0 // 筑巢冷却
    };
}

function createKitten(x, y, father, mother) {
    const cat = createCat(x, y, false);
    cat.growTimer = 0;
    cat.huntCount = 0;
    cat.parents.father = father;
    cat.parents.mother = mother;
    cat.name = generateName();
    return cat;
}

function generateCats() {
    cats = [];
    let tries = 0;
    while (cats.length < 5 && tries < 5 * 30) {
        tries++;
        const x = WORLD_BOUND.left + 20 + Math.random() * (WORLD_BOUND.right - WORLD_BOUND.left - 40);
        const y = WORLD_BOUND.top + 20 + Math.random() * (WORLD_BOUND.bottom - WORLD_BOUND.top - 40);
        let ok = true;
        for (const t of trees) if (Math.hypot(x - t.x, y - t.y) < TREE_COLLIDE_RADIUS + CAT_RADIUS) { ok = false; break; }
        if (ok) { cats.push(createCat(x, y)); }
    }
    if (cats.length < 2) {
        const fallbackPos = [[100,100], [200,200]];
        for (const [x,y] of fallbackPos) cats.push(createCat(x, y));
    }
}

// ========== 交配 ==========
function performMating(father, mother) {
    if (cats.length >= MAX_CATS) return false;
    if (father.gender === mother.gender) return false;
    if (father.growTimer < CAT_GROW_TIME || mother.growTimer < CAT_GROW_TIME) return false;
    if (father.breedCooldown > 0 || mother.breedCooldown > 0) return false;
    if (father.huntCount < CAT_BREED_REQUIRE || mother.huntCount < CAT_BREED_REQUIRE) return false;
    father.mate = mother;
    mother.mate = father;
    const kittens = [];
    for (let k = 0; k < CAT_LITTER_SIZE; k++) {
        let sx = (father.x + mother.x) / 2 + (Math.random() - 0.5) * 45;
        let sy = (father.y + mother.y) / 2 + (Math.random() - 0.5) * 45;
        if (checkCollision(sx, sy, CAT_RADIUS * 0.4)) { sx += 35; sy += 35; }
        const kitten = createKitten(sx, sy, father, mother);
        kittens.push(kitten);
    }
    cats.push(...kittens);
    mother.isLactating = true;
    mother.milkSupply = 20;
    father.kittens.push(...kittens);
    mother.kittens.push(...kittens);
    father.huntCount = 0;
    mother.huntCount = 0;
    father.breedCooldown = CAT_BREED_COOLDOWN;
    mother.breedCooldown = CAT_BREED_COOLDOWN;
    father.targetMate = null;
    mother.targetMate = null;
    return true;
}

// ========== 浮动文字 ==========
function addFloatingText(x, y, text, color = "#ffd700") {
    floatingTexts.push({
        x, y,
        text,
        color,
        life: 60,
        maxLife: 60,
        alpha: 1.0
    });
}

function updateFloatingTexts() {
    for (let i = floatingTexts.length - 1; i >= 0; i--) {
        const ft = floatingTexts[i];
        ft.life -= 1;
        ft.alpha = ft.life / ft.maxLife;
        if (ft.life <= 0) {
            floatingTexts.splice(i, 1);
        }
    }
}

// ========== 昼夜管理 ==========
function updateDayNight() {
    if (isDay) {
        dayTimer++;
        if (dayTimer >= DAY_LENGTH) {
            isDay = false;
            dayTimer = 0;
            nightTimer = 0;
            // 夜晚开始:处理猫和猎物的睡眠状态
            handleNightStart();
            timeDisplay.textContent = "🌙 夜晚";
        }
    } else {
        nightTimer++;
        if (nightTimer >= NIGHT_LENGTH) {
            isDay = true;
            nightTimer = 0;
            dayTimer = 0;
            // 天亮:唤醒所有生物
            handleDayStart();
            timeDisplay.textContent = "☀️ 白天";
        }
    }
}

function handleNightStart() {
    // 猫睡眠决策
    for (const cat of cats) {
        if (cat.isSleeping) continue; // 如果已睡则维持
        // 成年且非幼崽才考虑睡眠(幼崽可跟随母亲,暂不处理)
        const progress = cat.growTimer / CAT_GROW_TIME;
        if (progress < 0.33) continue; // 幼崽不独立睡眠

        const isHungry = cat.hungerTimer < CAT_HUNGER_STATE;
        // 饥饿猫有30%概率不睡,继续捕猎
        if (isHungry && Math.random() < 0.3) {
            cat.isSleeping = false;
            continue;
        }
        // 有窝且不饿 -> 回窝睡觉
        if (cat.nest && !isHungry) {
            cat.isSleeping = true;
            // 移动到窝的位置(可选,但为简化,直接标记位置)
            cat.targetX = cat.nest.x;
            cat.targetY = cat.nest.y;
            // 但实际移动会在update中处理
        } else if (!cat.nest) {
            // 无窝,原地睡觉(但不缓解饥饿,有惩罚)
            cat.isSleeping = true;
            cat.sleepPenalty = (cat.sleepPenalty || 0) + 1;
        } else {
            // 有窝但饥饿,且未抽中不睡 -> 仍睡觉,但饥饿不缓解(窝睡觉缓解饥饿?根据需求:窝睡觉可缓解但不能消除)
            cat.isSleeping = true;
        }
    }
    // 猎物睡眠:80%睡觉
    for (const prey of preys) {
        if (Math.random() < 0.8) {
            prey.isSleeping = true;
        } else {
            prey.isSleeping = false;
        }
    }
}

function handleDayStart() {
    for (const cat of cats) {
        cat.isSleeping = false;
        // 如果无窝睡眠惩罚累积,可在这里适当降低声望或健康(暂时只记录)
        if (cat.sleepPenalty > 0) {
            // 惩罚:降低一点声望或增加捕猎难度(这里只作为标记)
            cat.reputation = Math.max(0, cat.reputation - 1);
            cat.sleepPenalty = 0;
        }
    }
    for (const prey of preys) {
        prey.isSleeping = false;
    }
}

// ========== 猫筑巢逻辑 ==========
function tryBuildNest(cat) {
    // 条件:吃饱、非救助、非求偶、非睡觉、冷却结束
    if (cat.hungerTimer < CAT_FULL_THRESHOLD) return false;
    if (cat.isHelping || cat.targetMate || cat.isSleeping) return false;
    if (cat.buildNestCooldown > 0) return false;
    if (cat.nest) return false; // 已有窝

    // 检查周围环境:树木和荆棘数量
    let treeCount = 0, thornCount = 0;
    for (const tree of trees) {
        if (Math.hypot(tree.x - cat.x, tree.y - cat.y) < NEST_CHECK_RADIUS) treeCount++;
    }
    for (const thorn of thorns) {
        if (Math.hypot(thorn.x - cat.x, thorn.y - cat.y) < NEST_CHECK_RADIUS) thornCount++;
    }
    // 条件:至少1棵树且至少2个荆棘丛
    if (treeCount < 1 || thornCount < 2) return false;

    // 选择窝的位置:优先靠近已有窝(在NEST_PREFER_RADIUS内)
    let bestX = cat.x, bestY = cat.y;
    let bestScore = 0;
    // 尝试在周围随机偏移,评估位置
    for (let attempt = 0; attempt < 20; attempt++) {
        const angle = Math.random() * 2 * Math.PI;
        const dist = 20 + Math.random() * 40;
        const tx = cat.x + Math.cos(angle) * dist;
        const ty = cat.y + Math.sin(angle) * dist;
        if (!isPointInWorld(tx, ty)) continue;
        if (checkCollision(tx, ty, CAT_RADIUS)) continue;
        // 计算得分:附近已有窝数量(越近越好)
        let score = 0;
        for (const nest of nests) {
            const d = Math.hypot(nest.x - tx, nest.y - ty);
            if (d < NEST_PREFER_RADIUS) score += (NEST_PREFER_RADIUS - d) / NEST_PREFER_RADIUS;
        }
        // 随机加成
        score += Math.random() * 0.5;
        if (score > bestScore) {
            bestScore = score;
            bestX = tx;
            bestY = ty;
        }
    }

    // 创建窝
    const nest = {
        x: bestX,
        y: bestY,
        owner: cat
    };
    nests.push(nest);
    cat.nest = nest;
    cat.buildNestCooldown = 600; // 冷却10秒
    addFloatingText(bestX, bestY - 20, cat.name + " 建了窝", "#88dd88");
    return true;
}

// ========== 更新:猎物 ==========
function updateBreeding() {
    if (preys.length >= PREY_MAX_COUNT) return;
    for (let i = 0; i < preys.length; i++) {
        const a = preys[i];
        if (a.breedCooldown > 0 || a.eatenHerbs < FEED_REQUIRE) continue;
        for (let j = i + 1; j < preys.length; j++) {
            const b = preys[j];
            if (b.breedCooldown > 0 || b.eatenHerbs < FEED_REQUIRE) continue;
            if (Math.hypot(a.x - b.x, a.y - b.y) <= BREED_DISTANCE) {
                const cx = (a.x + b.x) / 2, cy = (a.y + b.y) / 2;
                for (let k = 0; k < BABY_COUNT; k++) {
                    let sx = cx + (Math.random() - 0.5) * 40;
                    let sy = cy + (Math.random() - 0.5) * 40;
                    if (checkCollision(sx, sy, PREY_RADIUS)) { sx += 30; sy += 30; }
                    if (preys.length < PREY_MAX_COUNT) preys.push(createPrey(sx, sy));
                }
                a.eatenHerbs = 0; b.eatenHerbs = 0;
                a.breedCooldown = 600; b.breedCooldown = 600;
                break;
            }
        }
    }
}

function updatePreys() {
    for (let i = preys.length - 1; i >= 0; i--) {
        const prey = preys[i];
        // 如果猎物在睡觉,不消耗饥饿,不移动
        if (prey.isSleeping) continue;

        prey.hungerTimer -= 1;
        if (prey.hungerTimer <= 0) { preys.splice(i, 1); continue; }

        prey.wanderTimer -= 1;
        if (prey.breedCooldown > 0) prey.breedCooldown--;
        prey.targetHerb = null;
        prey.targetMate = null;
        prey.fleeTarget = null;

        let nearestCat = null, minCatDist = Infinity;
        for (const cat of cats) {
            if (cat.isSleeping) continue; // 睡觉的猫不惊扰猎物
            const dx = cat.x - prey.x, dy = cat.y - prey.y;
            const dist = Math.hypot(dx, dy);
            if (dist > PREY_VIEW_RANGE) continue;
            const angleToCat = Math.atan2(dy, dx);
            let delta = angleToCat - prey.angle;
            while (delta > Math.PI) delta -= Math.PI * 2;
            while (delta < -Math.PI) delta += Math.PI * 2;
            if (Math.abs(delta) <= PREY_VIEW_ANGLE / 2 && !isLineBlocked(prey.x, prey.y, cat.x, cat.y)) {
                if (dist < minCatDist) { minCatDist = dist; nearestCat = cat; }
            }
        }

        let moveX = 0, moveY = 0;
        if (nearestCat !== null) {
            const dxAway = prey.x - nearestCat.x, dyAway = prey.y - nearestCat.y;
            const distToCat = Math.hypot(dxAway, dyAway);
            let fleeAngle = Math.atan2(dyAway, dxAway);
            prey.angle = fleeAngle;
            const testX = prey.x + Math.cos(fleeAngle) * 30;
            const testY = prey.y + Math.sin(fleeAngle) * 30;
            if (!isPointInWorld(testX, testY)) {
                fleeAngle += (Math.random() > 0.5 ? 1 : -1) * Math.PI / 4;
                prey.angle = fleeAngle;
            }
            let speedScale = 1;
            if (distToCat < 160) speedScale = 1 + (160 - distToCat) / 160 * 0.45;
            const speed = PREY_FLEE_SPEED * speedScale;
            moveX = Math.cos(fleeAngle) * speed;
            moveY = Math.sin(fleeAngle) * speed;
        } else {
            if (prey.eatenHerbs >= FEED_REQUIRE && prey.breedCooldown <= 0) {
                let nearestMate = null, minDist = Infinity;
                for (const other of preys) {
                    if (other === prey || other.eatenHerbs < FEED_REQUIRE || other.breedCooldown > 0 || other.isSleeping) continue;
                    const dx = other.x - prey.x, dy = other.y - prey.y;
                    const dist = Math.hypot(dx, dy);
                    if (dist > PREY_VIEW_RANGE || isLineBlocked(prey.x, prey.y, other.x, other.y)) continue;
                    const angleToTarget = Math.atan2(dy, dx);
                    let delta = angleToTarget - prey.angle;
                    while (delta > Math.PI) delta -= Math.PI * 2;
                    while (delta < -Math.PI) delta += Math.PI * 2;
                    if (Math.abs(delta) <= PREY_VIEW_ANGLE / 2 && dist < minDist) {
                        minDist = dist;
                        nearestMate = other;
                    }
                }
                prey.targetMate = nearestMate;
            }
            if (!prey.targetMate) {
                let nearestHerb = null, minDist = Infinity;
                for (const herb of herbs) {
                    const dx = herb.x - prey.x, dy = herb.y - prey.y;
                    const dist = Math.hypot(dx, dy);
                    if (dist > PREY_VIEW_RANGE || isLineBlocked(prey.x, prey.y, herb.x, herb.y)) continue;
                    const angleToTarget = Math.atan2(dy, dx);
                    let delta = angleToTarget - prey.angle;
                    while (delta > Math.PI) delta -= Math.PI * 2;
                    while (delta < -Math.PI) delta += Math.PI * 2;
                    if (Math.abs(delta) <= PREY_VIEW_ANGLE / 2 && dist < minDist) {
                        minDist = dist;
                        nearestHerb = herb;
                    }
                }
                prey.targetHerb = nearestHerb;
            }

            if (prey.targetMate) {
                const dx = prey.targetMate.x - prey.x, dy = prey.targetMate.y - prey.y;
                const dist = Math.hypot(dx, dy);
                prey.angle = Math.atan2(dy, dx);
                if (dist > BREED_DISTANCE) { moveX = (dx / dist) * PREY_SPEED; moveY = (dy / dist) * PREY_SPEED; }
            } else if (prey.targetHerb) {
                const dx = prey.targetHerb.x - prey.x, dy = prey.targetHerb.y - prey.y;
                const dist = Math.hypot(dx, dy);
                prey.angle = Math.atan2(dy, dx);
                if (dist > PREY_FEED_RANGE) { moveX = (dx / dist) * PREY_SPEED; moveY = (dy / dist) * PREY_SPEED; } else {
                    const idx = herbs.indexOf(prey.targetHerb);
                    if (idx > -1) herbs.splice(idx, 1);
                    prey.eatenHerbs += 1;
                    prey.hungerTimer = MAX_HUNGER_TIME;
                    prey.targetHerb = null;
                }
            } else {
                if (prey.wanderTimer <= 0) { prey.angle = Math.random() * Math.PI * 2; prey.wanderTimer = 90 + Math.random() * 140; }
                moveX = Math.cos(prey.angle) * PREY_SPEED * 0.65;
                moveY = Math.sin(prey.angle) * PREY_SPEED * 0.65;
            }
        }
        safeMove(prey, moveX, moveY, PREY_RADIUS);
    }
    updateBreeding();
}

// ========== 更新:猫 ==========
function updateCats() {
    // 先处理睡眠移动(回窝)
    for (const cat of cats) {
        if (cat.isSleeping) {
            // 如果猫有窝且不在窝旁,移动回窝
            if (cat.nest) {
                const dx = cat.nest.x - cat.x;
                const dy = cat.nest.y - cat.y;
                const dist = Math.hypot(dx, dy);
                if (dist > 10) {
                    const moveX = (dx / dist) * CAT_SPEED * 0.5;
                    const moveY = (dy / dist) * CAT_SPEED * 0.5;
                    safeMove(cat, moveX, moveY, CAT_RADIUS);
                }
            }
            // 睡眠时饥饿不减少(缓解但消除?饥饿睡眠可缓解但不能消除)
            if (cat.hungerTimer < CAT_HUNGER_MAX) {
                cat.hungerTimer += 0.2; // 缓慢恢复,但不会超过饥饿阈值
                if (cat.hungerTimer > CAT_HUNGER_STATE + 200) cat.hungerTimer = CAT_HUNGER_STATE + 200; // 最多恢复到不饿但不满
            }
            continue; // 睡眠时不做其他AI
        }
    }

    // 其他AI逻辑(与之前类似,但增加筑巢和昼夜影响)
    for (let i = cats.length - 1; i >= 0; i--) {
        const cat = cats[i];
        if (cat.isSleeping) continue; // 已处理

        // 饥饿递减(只有醒着才消耗)
        cat.hungerTimer -= 1;
        if (cat.hungerTimer <= 0) {
            if (cat.waitingForHelp) {
                for (const other of cats) {
                    if (other.helpingTarget === cat) {
                        other.helpingTarget = null;
                        other.isHelping = false;
                        other.carryingPrey = null;
                        other.helpAttemptTimer = 0;
                    }
                }
            }
            cats.splice(i, 1);
            continue;
        }

        if (cat.growTimer < CAT_GROW_TIME) cat.growTimer += 1;
        if (cat.breedCooldown > 0) cat.breedCooldown--;
        if (cat.buildNestCooldown > 0) cat.buildNestCooldown--;

        const progress = cat.growTimer / CAT_GROW_TIME;
        let stage = 2;
        if (progress < 0.33) stage = 0;
        else if (progress < 0.66) stage = 1;

        let scaleFactor = 1;
        if (stage === 0) scaleFactor = 0.4;
        else if (stage === 1) scaleFactor = 0.7;
        else scaleFactor = 1.0;
        const currentRadius = CAT_RADIUS * scaleFactor;

        // 哺乳母猫不能移动
        if (cat.isLactating && cat.kittens.length > 0) {
            if (cat.milkSupply > 0) {
                for (const kitten of cat.kittens) {
                    if (Math.hypot(kitten.x - cat.x, kitten.y - cat.y) < 40) {
                        cat.milkSupply -= 0.5;
                        kitten.growTimer += 2;
                    }
                }
                if (cat.milkSupply <= 0) cat.isLactating = false;
            } else {
                cat.isLactating = false;
            }
            cat.targetMate = null;
            cat.targetPrey = null;
            continue;
        }

        // 携带猎物送货
        if (cat.carryingPrey && cat.mate) {
            const target = cat.mate;
            const dx = target.x - cat.x, dy = target.y - cat.y;
            const dist = Math.hypot(dx, dy);
            cat.angle = Math.atan2(dy, dx);
            if (dist > 30) {
                const moveX = (dx / dist) * CAT_SPEED * 1.2;
                const moveY = (dy / dist) * CAT_SPEED * 1.2;
                safeMove(cat, moveX, moveY, currentRadius);
            } else {
                target.milkSupply += 30;
                target.isLactating = true;
                cat.carryingPrey = null;
                cat.targetMateLocation = null;
            }
            cat.targetMate = null;
            cat.targetPrey = null;
            continue;
        }

        // 被救猫等待
        if (cat.waitingForHelp) {
            let helperAlive = false;
            for (const other of cats) {
                if (other.helpingTarget === cat) {
                    helperAlive = true;
                    break;
                }
            }
            if (!helperAlive) {
                cat.waitingForHelp = false;
            } else {
                continue;
            }
        }

        const isHungry = cat.hungerTimer < CAT_HUNGER_STATE;
        const isFull = cat.hungerTimer > CAT_FULL_THRESHOLD;
        const canMate = (stage === 2) && cat.huntCount >= CAT_BREED_REQUIRE && cat.breedCooldown === 0;

        // 救助行为(施救者)
        if (cat.isHelping) {
            if (isHungry) {
                if (cat.helpingTarget) {
                    cat.helpingTarget.waitingForHelp = false;
                    cat.helpingTarget = null;
                }
                cat.isHelping = false;
                cat.carryingPrey = null;
                cat.helpAttemptTimer = 0;
            } else {
                if (cat.carryingPrey) {
                    const targetPos = cat.helpTargetPos;
                    if (targetPos) {
                        const dx = targetPos.x - cat.x;
                        const dy = targetPos.y - cat.y;
                        const dist = Math.hypot(dx, dy);
                        cat.angle = Math.atan2(dy, dx);
                        if (dist > 30) {
                            const moveX = (dx / dist) * CAT_SPEED * 1.2;
                            const moveY = (dy / dist) * CAT_SPEED * 1.2;
                            safeMove(cat, moveX, moveY, currentRadius);
                        } else {
                            if (cat.helpingTarget && cat.helpingTarget.waitingForHelp) {
                                cat.helpingTarget.hungerTimer = CAT_HUNGER_MAX;
                                cat.helpingTarget.waitingForHelp = false;
                                cat.reputation += 2;
                                cat.carryingPrey = null;
                                addFloatingText(cat.x, cat.y - 30, "喂食成功", "#8f8");
                            }
                            cat.helpingTarget = null;
                            cat.isHelping = false;
                            cat.helpTargetPos = null;
                            cat.helpAttemptTimer = 0;
                        }
                    } else {
                        cat.isHelping = false;
                        cat.carryingPrey = null;
                        cat.helpingTarget = null;
                        cat.helpAttemptTimer = 0;
                    }
                } else {
                    // 继续捕猎
                    cat.targetPrey = null;
                    let nearestPrey = null, minDist = Infinity;
                    for (const prey of preys) {
                        if (prey.isSleeping) continue; // 不捕猎睡觉的猎物
                        const dx = prey.x - cat.x, dy = prey.y - cat.y;
                        const dist = Math.hypot(dx, dy);
                        if (dist > CAT_VIEW_RANGE || isLineBlocked(cat.x, cat.y, prey.x, prey.y)) continue;
                        const angleToTarget = Math.atan2(dy, dx);
                        let delta = angleToTarget - cat.angle;
                        while (delta > Math.PI) delta -= Math.PI * 2;
                        while (delta < -Math.PI) delta += Math.PI * 2;
                        if (Math.abs(delta) <= CAT_VIEW_ANGLE / 2 && dist < minDist) {
                            minDist = dist;
                            nearestPrey = prey;
                        }
                    }
                    if (nearestPrey) {
                        cat.targetPrey = nearestPrey;
                        const dx = cat.targetPrey.x - cat.x;
                        const dy = cat.targetPrey.y - cat.y;
                        const dist = Math.hypot(dx, dy);
                        cat.angle = Math.atan2(dy, dx);
                        if (dist > CAT_HUNT_RANGE) {
                            let moveX, moveY;
                            if (cat.tryFlank) {
                                const flankOffset = cat.angle + (Math.random() > 0.5 ? 0.6 : -0.6);
                                moveX = Math.cos(flankOffset) * CAT_SPEED;
                                moveY = Math.sin(flankOffset) * CAT_SPEED;
                            } else {
                                moveX = (dx / dist) * CAT_SPEED;
                                moveY = (dy / dist) * CAT_SPEED;
                            }
                            safeMove(cat, moveX, moveY, currentRadius);
                        } else {
                            const idx = preys.indexOf(cat.targetPrey);
                            if (idx > -1) {
                                const prey = preys[idx];
                                preys.splice(idx, 1);
                                cat.huntCount += 1;
                                cat.hungerTimer = CAT_HUNGER_MAX;
                                cat.carryingPrey = prey;
                                cat.tryFlank = true;
                                cat.targetPrey = null;
                            }
                        }
                    } else {
                        cat.helpAttemptTimer += 1;
                        if (cat.helpAttemptTimer > 300) {
                            if (cat.helpingTarget) {
                                cat.helpingTarget.waitingForHelp = false;
                                cat.helpingTarget = null;
                            }
                            cat.isHelping = false;
                            cat.helpAttemptTimer = 0;
                        } else {
                            cat.wanderTimer -= 1;
                            if (cat.wanderTimer <= 0) {
                                cat.angle = Math.random() * Math.PI * 2;
                                cat.wanderTimer = 100 + Math.random() * 180;
                            }
                            const moveX = Math.cos(cat.angle) * CAT_SPEED * 0.7;
                            const moveY = Math.sin(cat.angle) * CAT_SPEED * 0.7;
                            safeMove(cat, moveX, moveY, currentRadius);
                        }
                    }
                }
                continue;
            }
        }

        // 救助检测(吃饱且不饥饿,且非救助中,且白天或夜晚但允许捕猎)
        if (isFull && !cat.isHelping && stage === 2) {
            let target = null;
            let minDist = Infinity;
            for (const other of cats) {
                if (other === cat) continue;
                if (other.hungerTimer >= CAT_HUNGER_STATE) continue;
                if (other.waitingForHelp) continue;
                const dx = other.x - cat.x, dy = other.y - cat.y;
                const dist = Math.hypot(dx, dy);
                if (dist > CAT_VIEW_RANGE) continue;
                if (isLineBlocked(cat.x, cat.y, other.x, other.y)) continue;
                const angleToOther = Math.atan2(dy, dx);
                let delta = angleToOther - cat.angle;
                while (delta > Math.PI) delta -= Math.PI * 2;
                while (delta < -Math.PI) delta += Math.PI * 2;
                if (Math.abs(delta) <= CAT_VIEW_ANGLE / 2 && dist < minDist) {
                    minDist = dist;
                    target = other;
                }
            }
            if (target) {
                cat.isHelping = true;
                cat.helpingTarget = target;
                cat.helpTargetPos = { x: target.x, y: target.y };
                cat.helpAttemptTimer = 0;
                target.waitingForHelp = true;
                addFloatingText(cat.x, cat.y - 30, "在这等着。", "#ffd700");
                continue;
            }
        }

        // 筑巢尝试(吃饱游荡时)
        if (isFull && !cat.isHelping && !cat.targetMate && !cat.targetPrey && !cat.nest && cat.buildNestCooldown === 0) {
            if (tryBuildNest(cat)) {
                // 筑巢成功,本帧不再移动
                continue;
            }
        }

        // 求偶
        cat.targetMate = null;
        if (canMate && !isHungry && !cat.isHelping) {
            let nearestMate = null, minDist = Infinity;
            for (const other of cats) {
                if (other === cat) continue;
                if (other.gender === cat.gender) continue;
                if (other.growTimer < CAT_GROW_TIME) continue;
                if (other.breedCooldown > 0) continue;
                if (other.huntCount < CAT_BREED_REQUIRE) continue;
                if (other.isSleeping) continue; // 睡觉的不能交配
                const dx = other.x - cat.x, dy = other.y - cat.y;
                const dist = Math.hypot(dx, dy);
                if (dist > CAT_VIEW_RANGE) continue;
                if (isLineBlocked(cat.x, cat.y, other.x, other.y)) continue;
                const angleToOther = Math.atan2(dy, dx);
                let delta = angleToOther - cat.angle;
                while (delta > Math.PI) delta -= Math.PI * 2;
                while (delta < -Math.PI) delta += Math.PI * 2;
                if (Math.abs(delta) <= CAT_VIEW_ANGLE / 2 && dist < minDist) {
                    minDist = dist;
                    nearestMate = other;
                }
            }
            cat.targetMate = nearestMate;
        }

        if (cat.targetMate) {
            const dx = cat.targetMate.x - cat.x;
            const dy = cat.targetMate.y - cat.y;
            const dist = Math.hypot(dx, dy);
            cat.angle = Math.atan2(dy, dx);
            if (dist > CAT_BREED_DISTANCE) {
                const moveX = (dx / dist) * CAT_SPEED;
                const moveY = (dy / dist) * CAT_SPEED;
                safeMove(cat, moveX, moveY, currentRadius);
            } else {
                const father = cat.gender === "male" ? cat : cat.targetMate;
                const mother = cat.gender === "female" ? cat : cat.targetMate;
                const success = performMating(father, mother);
                cat.targetMate = null;
                if (cat.mate) cat.mate.targetMate = null;
                if (!success) cat.breedCooldown = 60;
            }
            continue;
        }

        // 捕猎(仅当不饿且非救助,且猎物未睡觉)
        cat.targetPrey = null;
        if (stage !== 0 && !isFull) {
            let nearestPrey = null, minDist = Infinity;
            for (const prey of preys) {
                if (prey.isSleeping) continue;
                const dx = prey.x - cat.x, dy = prey.y - cat.y;
                const dist = Math.hypot(dx, dy);
                if (dist > CAT_VIEW_RANGE || isLineBlocked(cat.x, cat.y, prey.x, prey.y)) continue;
                const angleToTarget = Math.atan2(dy, dx);
                let delta = angleToTarget - cat.angle;
                while (delta > Math.PI) delta -= Math.PI * 2;
                while (delta < -Math.PI) delta += Math.PI * 2;
                if (Math.abs(delta) <= CAT_VIEW_ANGLE / 2 && dist < minDist) {
                    minDist = dist;
                    nearestPrey = prey;
                }
            }
            cat.targetPrey = nearestPrey;
        }

        if (cat.targetPrey) {
            const dx = cat.targetPrey.x - cat.x;
            const dy = cat.targetPrey.y - cat.y;
            const dist = Math.hypot(dx, dy);
            cat.angle = Math.atan2(dy, dx);
            if (dist > CAT_HUNT_RANGE) {
                let moveX, moveY;
                if (cat.tryFlank) {
                    const flankOffset = cat.angle + (Math.random() > 0.5 ? 0.6 : -0.6);
                    moveX = Math.cos(flankOffset) * CAT_SPEED;
                    moveY = Math.sin(flankOffset) * CAT_SPEED;
                } else {
                    moveX = (dx / dist) * CAT_SPEED;
                    moveY = (dy / dist) * CAT_SPEED;
                }
                safeMove(cat, moveX, moveY, currentRadius);
            } else {
                const idx = preys.indexOf(cat.targetPrey);
                if (idx > -1) {
                    const prey = preys[idx];
                    preys.splice(idx, 1);
                    cat.huntCount += 1;
                    cat.hungerTimer = CAT_HUNGER_MAX;
                    if (!isHungry && cat.mate && cat.kittens.length > 0 && stage === 2 && !cat.isHelping) {
                        cat.carryingPrey = prey;
                        cat.targetMateLocation = { x: cat.mate.x, y: cat.mate.y };
                    }
                    cat.tryFlank = true;
                }
                cat.targetPrey = null;
            }
        } else {
            // 闲逛
            cat.wanderTimer -= 1;
            if (cat.wanderTimer <= 0) {
                cat.angle = Math.random() * Math.PI * 2;
                cat.wanderTimer = 100 + Math.random() * 180;
            }
            const moveX = Math.cos(cat.angle) * CAT_SPEED * 0.7;
            const moveY = Math.sin(cat.angle) * CAT_SPEED * 0.7;
            safeMove(cat, moveX, moveY, currentRadius);
        }
    }
}

// ========== 全局更新 ==========
function updateWorld() {
    herbRespawnTimer++;
    if (herbRespawnTimer >= HERB_RESPAWN_INTERVAL) {
        herbRespawnTimer = 0;
        trySpawnHerb();
    }
    updateFloatingTexts();
    updateDayNight();
}

// ========== 面板更新 ==========
function updatePopulationPanel() {
    let adult = 0, kid = 0;
    for (const c of cats) {
        if (c.growTimer >= CAT_GROW_TIME) adult++;
        else kid++;
    }
    let followText = "无";
    if (followedCat) {
        const genderText = followedCat.gender === "male" ? "公猫" : "母猫";
        followText = `${genderText} | 捕猎:${followedCat.huntCount}`;
    }
    populationPanel.textContent = `猎物:${preys.length} / 草:${herbs.length} / 成年猫:${adult} / 幼猫:${kid} / 跟随:${followText}`;
}

function updateDetailPanel() {
    if (followedCat && !cats.includes(followedCat)) {
        followedCat = null;
    }
    if (!followedCat) {
        detailPanel.textContent = "点击一只猫查看详情";
        return;
    }
    const c = followedCat;
    const progress = c.growTimer / CAT_GROW_TIME;
    let stageStr = "成年";
    if (progress < 0.33) stageStr = "幼崽";
    else if (progress < 0.66) stageStr = "幼猫";

    const hungerStr = c.hungerTimer < CAT_HUNGER_STATE ? "饥饿" : "正常";
    const genderStr = c.gender === "male" ? "公" : "母";
    const statusParts = [];
    if (c.isLactating) statusParts.push("哺乳中");
    if (c.carryingPrey) statusParts.push("携带猎物");
    if (c.mate) statusParts.push("有配偶");
    if (c.isHelping) statusParts.push("救助中");
    if (c.waitingForHelp) statusParts.push("等待救助");
    if (c.isSleeping) statusParts.push("💤 睡觉");
    if (c.nest) statusParts.push("有窝");
    const statusStr = statusParts.length ? statusParts.join("、") : "无特殊";

    const detail = `姓名:${c.name} | 性别:${genderStr} | 年龄:${stageStr} | 饥饿:${hungerStr} | 捕猎:${c.huntCount} | 幼崽:${c.kittens.length} | 声望:${c.reputation} | 状态:${statusStr}`;
    detailPanel.textContent = detail;
}

// ========== 渲染 ==========
function renderMap() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();

    if (followedCat) {
        const targetX = canvas.width / 2 - followedCat.x * scale;
        const targetY = canvas.height / 2 - followedCat.y * scale;
        offsetX += (targetX - offsetX) * 0.08;
        offsetY += (targetY - offsetY) * 0.08;
    }

    ctx.translate(offsetX, offsetY);
    ctx.scale(scale, scale);

    // ----- 地面内容(受昼夜滤镜影响) -----
    if (!isDay) {
        ctx.filter = "brightness(0.4)";
    }

    // 草地
    ctx.fillStyle = GRASS_COLOR;
    ctx.fillRect(-3000, -3000, 6000, 6000);

    // 网格
    ctx.beginPath();
    ctx.setLineDash(DASH_PATTERN);
    ctx.strokeStyle = GRID_COLOR;
    ctx.globalAlpha = GRID_ALPHA;
    ctx.lineWidth = 1;
    const p1 = screenToWorld(0, 0);
    const p2 = screenToWorld(canvas.width, canvas.height);
    const startX = Math.floor(p1.x / GRID_SIZE) * GRID_SIZE;
    const startY = Math.floor(p1.y / GRID_SIZE) * GRID_SIZE;
    for (let x = startX; x <= p2.x; x += GRID_SIZE) { ctx.moveTo(x, p1.y); ctx.lineTo(x, p2.y); }
    for (let y = startY; y <= p2.y; y += GRID_SIZE) { ctx.moveTo(p1.x, y); ctx.lineTo(p2.x, y); }
    ctx.stroke();
    ctx.globalAlpha = 1;
    ctx.setLineDash([]);

    // 植物
    ctx.fillStyle = HERB_COLOR;
    for (const herb of herbs) {
        ctx.beginPath();
        ctx.moveTo(herb.x, herb.y - HERB_SIZE);
        ctx.lineTo(herb.x - HERB_SIZE * 0.7, herb.y + HERB_SIZE * 0.6);
        ctx.lineTo(herb.x + HERB_SIZE * 0.7, herb.y + HERB_SIZE * 0.6);
        ctx.closePath();
        ctx.fill();
    }

    // 灌木丛(半透明,显示网格)
    ctx.fillStyle = "rgba(0,80,0,0.3)";
    for (const bush of bushes) {
        ctx.beginPath();
        ctx.arc(bush.x, bush.y, BUSH_RADIUS, 0, Math.PI * 2);
        ctx.fill();
    }

    // 荆棘丛(实心深绿 + 黑色叉)
    ctx.fillStyle = "#1a4a1a";
    for (const thorn of thorns) {
        ctx.beginPath();
        ctx.arc(thorn.x, thorn.y, THORN_RADIUS, 0, Math.PI * 2);
        ctx.fill();
        // 黑色叉
        ctx.strokeStyle = "#000";
        ctx.lineWidth = 3;
        const offset = THORN_RADIUS * 0.6;
        ctx.beginPath();
        ctx.moveTo(thorn.x - offset, thorn.y - offset);
        ctx.lineTo(thorn.x + offset, thorn.y + offset);
        ctx.moveTo(thorn.x + offset, thorn.y - offset);
        ctx.lineTo(thorn.x - offset, thorn.y + offset);
        ctx.stroke();
    }

    // 树木
    ctx.fillStyle = TREE_COLOR;
    for (const tree of trees) {
        ctx.beginPath();
        ctx.arc(tree.x, tree.y, TREE_RADIUS, 0, Math.PI * 2);
        ctx.fill();
    }

    // 猎物(睡觉标记小Z)
    for (const prey of preys) {
        ctx.fillStyle = prey.eatenHerbs >= FEED_REQUIRE ? (prey.targetMate ? "#555" : "#222") : "#111";
        ctx.beginPath();
        ctx.arc(prey.x, prey.y, PREY_RADIUS, 0, Math.PI * 2);
        ctx.fill();
        if (prey.isSleeping) {
            ctx.fillStyle = "#ccc";
            ctx.font = "12px system-ui";
            ctx.textAlign = "center";
            ctx.textBaseline = "bottom";
            ctx.fillText("Z", prey.x, prey.y - PREY_RADIUS - 2);
        }
    }

    // 猫视野(不应用滤镜)
    ctx.filter = "none"; // 视野不受变暗影响
    ctx.fillStyle = "rgba(242,166,90,0.12)";
    ctx.strokeStyle = "rgba(242,166,90,0.35)";
    ctx.lineWidth = 1;
    for (const cat of cats) {
        if (cat.isSleeping) continue; // 睡觉无视野
        const progress = Math.min(1, cat.growTimer / CAT_GROW_TIME);
        let sf = 1;
        if (progress < 0.33) sf = 0.4;
        else if (progress < 0.66) sf = 0.7;
        else sf = 1.0;
        const r = CAT_RADIUS * sf;
        ctx.beginPath();
        ctx.moveTo(cat.x, cat.y);
        ctx.arc(cat.x, cat.y, CAT_VIEW_RANGE * sf, cat.angle - CAT_VIEW_ANGLE / 2, cat.angle + CAT_VIEW_ANGLE / 2);
        ctx.closePath();
        ctx.fill();
        ctx.stroke();
    }

    // 猫本体(应用滤镜)
    if (!isDay) {
        ctx.filter = "brightness(0.4)";
    } else {
        ctx.filter = "none";
    }

    for (const cat of cats) {
        const progress = Math.min(1, cat.growTimer / CAT_GROW_TIME);
        let sf = 1;
        if (progress < 0.33) sf = 0.4;
        else if (progress < 0.66) sf = 0.7;
        else sf = 1.0;
        const r = CAT_RADIUS * sf;
        const isAdult = progress >= 1;
        const canBreed = isAdult && cat.huntCount >= CAT_BREED_REQUIRE && cat.breedCooldown === 0;

        // 高亮
        if (cat === followedCat) {
            ctx.beginPath();
            ctx.strokeStyle = "#fff";
            ctx.lineWidth = 3;
            ctx.arc(cat.x, cat.y, r + 10, 0, Math.PI * 2);
            ctx.stroke();
        }
        // 可繁殖光环
        if (canBreed) {
            ctx.beginPath();
            ctx.strokeStyle = "#ff88bb";
            ctx.lineWidth = 2;
            ctx.arc(cat.x, cat.y, r + 6, 0, Math.PI * 2);
            ctx.stroke();
        }
        // 饥饿红圈
        if (cat.hungerTimer < CAT_HUNGER_STATE) {
            ctx.beginPath();
            ctx.strokeStyle = "rgba(255, 0, 0, 0.6)";
            ctx.lineWidth = 2;
            ctx.arc(cat.x, cat.y, r + 4, 0, Math.PI * 2);
            ctx.stroke();
        }

        let color = CAT_COLOR;
        if (cat.carryingPrey) color = "#3a86ff";
        if (cat.waitingForHelp) color = "#ffaa44";
        if (cat.isSleeping) color = "#555555";
        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.arc(cat.x, cat.y, r, 0, Math.PI * 2);
        ctx.fill();

        ctx.fillStyle = "#995511";
        ctx.beginPath();
        ctx.arc(cat.x + Math.cos(cat.angle) * (r - 3), cat.y + Math.sin(cat.angle) * (r - 3), 3, 0, Math.PI * 2);
        ctx.fill();

        // 睡眠标记“💤”在猫上方
        if (cat.isSleeping) {
            ctx.fillStyle = "#aaddff";
            ctx.font = "18px system-ui";
            ctx.textAlign = "center";
            ctx.textBaseline = "bottom";
            ctx.fillText("💤", cat.x, cat.y - r - 6);
        }
    }

    // 窝(虚线圆 + 名字)
    ctx.filter = "none"; // 窝文字不受滤镜
    for (const nest of nests) {
        ctx.setLineDash([5,5]);
        ctx.strokeStyle = "#ffffff";
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.arc(nest.x, nest.y, CAT_RADIUS + 4, 0, Math.PI * 2);
        ctx.stroke();
        ctx.setLineDash([]);
        // 显示窝的名字
        ctx.fillStyle = "#ddd";
        ctx.font = "12px system-ui";
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";
        ctx.fillText(nest.owner.name + " 的窝", nest.x, nest.y - CAT_RADIUS - 8);
    }

    // 边界
    ctx.filter = "none";
    ctx.strokeStyle = "#000";
    ctx.lineWidth = 4;
    ctx.strokeRect(WORLD_BOUND.left, WORLD_BOUND.top, WORLD_BOUND.right - WORLD_BOUND.left, WORLD_BOUND.bottom - WORLD_BOUND.top);

    ctx.restore(); // 恢复到屏幕坐标系

    // ----- 在屏幕坐标系绘制文字(固定大小) -----
    // 猫名字和性别
    for (const cat of cats) {
        const screenX = cat.x * scale + offsetX;
        const screenY = cat.y * scale + offsetY;
        const progress = Math.min(1, cat.growTimer / CAT_GROW_TIME);
        let sf = 1;
        if (progress < 0.33) sf = 0.4;
        else if (progress < 0.66) sf = 0.7;
        else sf = 1.0;
        const r = CAT_RADIUS * sf * scale;

        const symbol = cat.gender === "male" ? MALE_SYMBOL : FEMALE_SYMBOL;
        const displayText = `(${symbol}) ${cat.name}`;
        ctx.save();
        ctx.font = "bold 14px system-ui";
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";
        ctx.fillStyle = "#fff";
        ctx.shadowColor = "rgba(0,0,0,0.9)";
        ctx.shadowBlur = 6;
        ctx.fillText(displayText, screenX, screenY - r - 6);
        ctx.restore();
    }

    // 浮动文字(也是固定大小)
    for (const ft of floatingTexts) {
        const screenX = ft.x * scale + offsetX;
        const screenY = ft.y * scale + offsetY;
        ctx.save();
        ctx.globalAlpha = ft.alpha;
        ctx.font = "bold 20px system-ui";
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";
        ctx.shadowColor = "rgba(0,0,0,0.9)";
        ctx.shadowBlur = 8;
        ctx.fillStyle = ft.color || "#ffd700";
        ctx.fillText(ft.text, screenX, screenY);
        ctx.restore();
    }
}

// ========== 交互 ==========
function getMouseScreenPos(e) {
    if (e.touches) return { x: e.touches[0].clientX, y: e.touches[0].clientY };
    return { x: e.clientX, y: e.clientY };
}

function handlePointerDown(e) {
    const pos = getMouseScreenPos(e);
    pointerDownX = pos.x;
    pointerDownY = pos.y;
    pointerDownTime = Date.now();
    isClick = true;
}

function handlePointerUp(e) {
    if (!isClick) return;
    const pos = getMouseScreenPos(e);
    const dx = pos.x - pointerDownX;
    const dy = pos.y - pointerDownY;
    const dist = Math.hypot(dx, dy);
    const elapsed = Date.now() - pointerDownTime;
    if (dist < 10 && elapsed < 300) {
        const canvasPos = getCanvasCoords(pos.x, pos.y);
        const world = screenToWorld(canvasPos.x, canvasPos.y);
        const pixelRatio = getPixelRatio();
        let clicked = null;
        for (const cat of cats) {
            const progress = Math.min(1, cat.growTimer / CAT_GROW_TIME);
            let sf = 1;
            if (progress < 0.33) sf = 0.4;
            else if (progress < 0.66) sf = 0.7;
            else sf = 1.0;
            const r = CAT_RADIUS * sf;
            const logicHitRadius = Math.max(30, 30 / pixelRatio);
            if (Math.hypot(world.x - cat.x, world.y - cat.y) <= r + logicHitRadius) {
                clicked = cat;
                break;
            }
        }
        if (clicked) {
            followedCat = clicked;
            isDragging = false;
            return;
        } else {
            followedCat = null;
        }
    }
}

function handlePointerMove(e) {
    const pos = getMouseScreenPos(e);
    if (isClick) {
        const dx = pos.x - pointerDownX;
        const dy = pos.y - pointerDownY;
        if (Math.hypot(dx, dy) > 10) {
            isClick = false;
            isDragging = true;
            dragStartX = pointerDownX;
            dragStartY = pointerDownY;
            startOffsetX = offsetX;
            startOffsetY = offsetY;
        }
    }
    if (isDragging) {
        const pixelRatio = getPixelRatio();
        const ddx = (pos.x - dragStartX) * pixelRatio;
        const ddy = (pos.y - dragStartY) * pixelRatio;
        offsetX = startOffsetX + ddx;
        offsetY = startOffsetY + ddy;
    }
}

function handlePointerCancel() {
    isDragging = false;
    isClick = false;
}

canvas.addEventListener("mousedown", handlePointerDown);
window.addEventListener("mousemove", handlePointerMove);
window.addEventListener("mouseup", handlePointerUp);

canvas.addEventListener("touchstart", (e) => {
    if (e.touches.length === 1) {
        const touch = e.touches[0];
        handlePointerDown({ clientX: touch.clientX, clientY: touch.clientY });
    } else if (e.touches.length === 2) {
        lastTouchDist = Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY);
        isDragging = false;
        isClick = false;
    }
}, { passive: true });

canvas.addEventListener("touchmove", (e) => {
    e.preventDefault();
    if (e.touches.length === 1) {
        const touch = e.touches[0];
        handlePointerMove({ clientX: touch.clientX, clientY: touch.clientY });
    } else if (e.touches.length === 2) {
        const dist = Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY);
        const cx = (e.touches[0].clientX + e.touches[1].clientX) / 2;
        const cy = (e.touches[0].clientY + e.touches[1].clientY) / 2;
        const canvasPos = getCanvasCoords(cx, cy);
        const wBefore = screenToWorld(canvasPos.x, canvasPos.y);
        const ratio = dist / lastTouchDist;
        scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale * ratio));
        lastTouchDist = dist;
        const wAfter = screenToWorld(canvasPos.x, canvasPos.y);
        offsetX += (wAfter.x - wBefore.x) * scale;
        offsetY += (wAfter.y - wBefore.y) * scale;
    }
}, { passive: false });

canvas.addEventListener("touchend", (e) => {
    if (e.touches.length === 0) {
        const touch = e.changedTouches[0];
        if (touch) handlePointerUp({ clientX: touch.clientX, clientY: touch.clientY });
        else handlePointerUp({ clientX: pointerDownX, clientY: pointerDownY });
    }
});
canvas.addEventListener("touchcancel", handlePointerCancel);

canvas.addEventListener("wheel", (e) => {
    e.preventDefault();
    const pos = { x: e.clientX, y: e.clientY };
    const canvasPos = getCanvasCoords(pos.x, pos.y);
    const wBefore = screenToWorld(canvasPos.x, canvasPos.y);
    const zoom = e.deltaY > 0 ? -0.12 : 0.12;
    scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale + zoom));
    const wAfter = screenToWorld(canvasPos.x, canvasPos.y);
    offsetX += (wAfter.x - wBefore.x) * scale;
    offsetY += (wAfter.y - wBefore.y) * scale;
}, { passive: false });

// ========== 加速 ==========
function setSpeed(s) {
    speedMultiplier = s;
    document.querySelectorAll('.speed-control button').forEach(btn => btn.classList.remove('active'));
    const map = {1:'speed1x', 2:'speed2x', 5:'speed5x'};
    document.getElementById(map[s]).classList.add('active');
}

// ========== 重置 ==========
function resetWorld() {
    trees.length = 0;
    herbs.length = 0;
    preys.length = 0;
    cats.length = 0;
    bushes.length = 0;
    thorns.length = 0;
    nests.length = 0;
    floatingTexts = [];
    followedCat = null;
    isDay = true;
    dayTimer = 0;
    nightTimer = 0;
    timeDisplay.textContent = "☀️ 白天";
    generateTrees();
    generateHerbs();
    generatePreys();
    generateBushes();
    generateThorns();
    generateCats();
    offsetX = 0;
    offsetY = 0;
    scale = 1.0;
}

// ========== 主循环 ==========
function gameLoop() {
    for (let t = 0; t < speedMultiplier; t++) {
        updateWorld();
        updatePreys();
        updateCats();
    }
    updatePopulationPanel();
    updateDetailPanel();
    renderMap();
    requestAnimationFrame(gameLoop);
}

// 初始化
generateTrees();
generateHerbs();
generatePreys();
generateBushes();
generateThorns();
generateCats();
gameLoop();

window.setSpeed = setSpeed;
window.resetWorld = resetWorld;

};
</script>
</body>
</html>

Game Source: 猫武士 · 演替兴衰(完整版)

Creator: EpicCoder88

Libraries: none

Complexity: complex (1823 lines, 65.9 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: game-epiccoder88" to link back to the original. Then publish at arcadelab.ai/publish.