呆鸟修仙 占卜、预测、人缘系统


# 占卜、预测、人缘系统

44.png

本文档详细说明占卜、预测、人缘三大AI功能的数据逻辑和使用规范。

## 功能概述

这三个功能都是基于大语言模型(LLM)的AI服务,为用户提供个性化建议和预测。

### 功能对比

| 功能 | 用途 | 每日次数 | 大模型 | 特点 |
|------|------|---------|--------|------|
| 占卜 | 周运预测 | 3次 | Doubao-Seed | 64卦象 + AI解读 |
| 预测 | 事件预测 | 3次 | Doubao-Seed | 事件分析 + 建议 |
| 人缘 | 人缘测试 | 3次 | Doubao-Seed | 关系分析 + 建议 |

## 数据库存储

所有次数管理都存储在 `user_permissions` 表中:

```sql
-- 占卜相关
divination_count          -- 已用次数
divination_max_daily      -- 每日上限(默认3)
last_divination_used_at   -- 最后使用时间

-- 预测相关
prediction_count          -- 已用次数
prediction_max_daily      -- 每日上限(默认3)
last_prediction_used_at   -- 最后使用时间

-- 人缘相关
affinity_count            -- 已用次数
affinity_max_daily        -- 每日上限(默认3)
last_affinity_used_at     -- 最后使用时间

-- 打坐任务(解锁次数)
has_meditation_for_prediction   -- 预测打坐任务完成状态
has_meditation_for_divination   -- 占卜打坐任务完成状态
has_meditation_for_affinity     -- 人缘打坐任务完成状态
```

## 占卜系统

### 功能说明

基于64卦象的周运预测,AI解读卦象含义并提供建议。

### 占卜流程

```
用户请求占卜
    ↓
检查剩余次数
    ↓
随机抽取卦象(1-64)
    ↓
调用大模型解读
    ↓
扣除次数
    ↓
返回卦象和解读
```

### API接口

**接口**: `POST /api/divination/perform`

**请求参数**:
```json
{
  "userId": "uuid"
}
```

**响应示例**:
```json
{
  "success": true,
  "gua": {
    "id": 1,
    "name": "乾卦",
    "emoji": "☰",
    "rarity": "legendary",
    "symbol": "天行健,君子以自强不息",
    "meaning": "大吉之象,宜进取,忌懈怠"
  },
  "interpretation": "本周运势大好,事业发展顺利,宜采取积极行动...",
  "advice": ["保持积极心态", "把握机遇", "注意劳逸结合"],
  "remainingCount": 2
}
```

### 卦象数据

**文件**: `src/data/GuaDatabase.ts`

```typescript
export interface GuaCard {
  id: number;              // 1-64
  name: string;            // 卦名
  emoji: string;           // 卦象符号
  rarity: "common" | "rare" | "epic" | "legendary";
  symbol: string;          // 卦辞
  meaning: string;         // 基本含义
}

export const GUA_DATABASE: Record<number, GuaCard> = {
  1: {
    id: 1,
    name: "乾卦",
    emoji: "☰",
    rarity: "legendary",
    symbol: "天行健,君子以自强不息",
    meaning: "大吉之象,宜进取,忌懈怠"
  },
  // ... 64卦
};
```

### AI提示词模板

```typescript
const DIVINATION_PROMPT = `
你是一位精通易经占卜的修仙大师。用户抽到了【${guaName}】(${guaSymbol})。

卦象含义:${guaMeaning}

请从以下角度为用户解读本周运势:
1. 事业运(工作、学业、修仙)
2. 财运(灵气、卡牌、道具)
3. 感情运(好友、社交)
4. 健康运(身心状态)

请给出3条具体建议,每条建议不超过20字。

返回格式:
本周运势:[简短总结]
解读:[详细解读,100-200字]
建议:
1. [建议1]
2. [建议2]
3. [建议3]
`;
```

## 预测系统

### 功能说明

基于用户描述的事件进行分析预测,提供决策建议。

### 预测流程

```
用户输入事件描述
    ↓
检查剩余次数
    ↓
调用大模型分析
    ↓
扣除次数
    ↓
返回预测和建议
```

### API接口

**接口**: `POST /api/prediction/analyze`

**请求参数**:
```json
{
  "userId": "uuid",
  "question": "我想挑战下一关,能成功吗?",
  "context": {
    "level": 10,
    "realm": "元婴期",
    "maxScore": 500
  }
}
```

**响应示例**:
```json
{
  "success": true,
  "prediction": "根据您目前的修为和关卡难度,成功率约70%",
  "analysis": "您已达到元婴期,实力较强。第10关目标分数为1000分...",
  "advice": [
    "提升体型到200%以上",
    "优先收集传说级灵气",
    "避开追踪型敌人"
  ],
  "confidence": 0.7,
  "remainingCount": 2
}
```

### AI提示词模板

```typescript
const PREDICTION_PROMPT = `
你是一位精通预测未来的修仙高人。

用户提问:${question}

用户当前状态:
- 境界:${realm}
- 最高关卡:${level}
- 最高分数:${maxScore}

请从以下角度分析:
1. 成功概率(0-100%)
2. 关键因素
3. 潜在风险
4. 应对策略

返回格式:
预测:[简短预测]
成功率:XX%
分析:[详细分析,150-200字]
建议:
1. [建议1]
2. [建议2]
3. [建议3]
信心度:XX%
`;
```

## 人缘系统

### 功能说明

分析用户的人际关系和社交运势,提供社交建议。

### 人缘测试流程

```
用户请求人缘测试
    ↓
检查剩余次数
    ↓
调用大模型分析
    ↓
扣除次数
    ↓
返回人缘分析和建议
```

### API接口

**接口**: `POST /api/affinity/analyze`

**请求参数**:
```json
{
  "userId": "uuid",
  "type": "self" // 或 "friend"
}
```

**响应示例**:
```json
{
  "success": true,
  "analysis": "您的人缘运势较好,朋友关系和谐",
  "socialScore": 85,
  "characteristics": [
    "待人真诚",
    "乐于助人",
    "幽默风趣"
  ],
  "advice": [
    "主动邀请新朋友",
    "多参与游戏互动",
    "分享游戏心得"
  ],
  "remainingCount": 2
}
```

### AI提示词模板

```typescript
const AFFINITY_PROMPT = `
你是一位擅长分析人际关系的修仙智者。

用户当前状态:
- 累计邀请好友:${inviteCount}人
- 好友总数:${friendCount}人
- 境界:${realm}

请从以下角度分析用户的人缘:
1. 社交能力评分(0-100)
2. 性格特点(3个关键词)
3. 人缘优势
4. 改进建议

返回格式:
人缘分析:[简短总结]
社交评分:XX分
性格特点:[特点1]、[特点2]、[特点3]
优势:[1-2句话]
建议:
1. [建议1]
2. [建议2]
3. [建议3]
`;
```

## 通用功能

### 次数管理

#### 检查次数

```typescript
async function checkUsageCount(userId: string, type: 'divination' | 'prediction' | 'affinity') {
  const db = await getDb();
  const result = await db.execute(sql`
    SELECT
      ${type}_count as usedCount,
      ${type}_max_daily as maxDaily,
      last_reset_date as lastResetDate
    FROM user_permissions
    WHERE user_id = ${userId}
  `);

  const { usedCount, maxDaily, lastResetDate } = result.rows[0];

  // 检查是否需要重置
  const today = new Date().toISOString().split('T')[0];
  if (lastResetDate !== today) {
    await resetDailyCount(userId, type);
    return { usedCount: 0, maxDaily };
  }

  return { usedCount, maxDaily };
}
```

#### 扣除次数

```typescript
async function decrementCount(userId: string, type: 'divination' | 'prediction' | 'affinity') {
  const db = await getDb();
  await db.execute(sql`
    UPDATE user_permissions
    SET
      ${type}_count = ${type}_count + 1,
      last_${type}_used_at = NOW()
    WHERE user_id = ${userId}
  `);
}
```

#### 每日重置

```typescript
async function resetDailyCount(userId: string, type: 'divination' | 'prediction' | 'affinity') {
  const db = await getDb();
  const today = new Date().toISOString().split('T')[0];
  await db.execute(sql`
    UPDATE user_permissions
    SET
      ${type}_count = 0,
      last_reset_date = ${today}
    WHERE user_id = ${userId}
  `);
}
```

### 会员加成

会员用户拥有额外次数:

```typescript
async function getTotalCount(userId: string, type: 'divination' | 'prediction' | 'affinity') {
  const db = await getDb();
  const result = await db.execute(sql`
    SELECT
      ${type}_count as usedCount,
      ${type}_max_daily as maxDaily,
      premium_${type}_count as premiumCount,
      is_premium as isPremium
    FROM user_permissions
    WHERE user_id = ${userId}
  `);

  const { usedCount, maxDaily, premiumCount, isPremium } = result.rows[0];

  const totalCount = maxDaily + (isPremium ? premiumCount : 0);

  return {
    used: usedCount,
    free: maxDaily - usedCount,
    premium: premiumCount,
    total: totalCount
  };
}
```

### 打坐解锁机制

打坐完成可以解锁1次使用机会:

```typescript
async function unlockWithMeditation(userId: string, type: 'divination' | 'prediction' | 'affinity') {
  const db = await getDb();
  const flag = `has_meditation_for_${type}`;

  const result = await db.execute(sql`
    SELECT ${flag} FROM user_permissions WHERE user_id = ${userId}
  `);

  if (result.rows[0][flag]) {
    await db.execute(sql`
      UPDATE user_permissions
      SET ${flag} = false
      WHERE user_id = ${userId}
    `);
    return true; // 解锁成功
  }

  return false; // 未完成打坐任务
}
```

## 集成大模型

### 使用 Doubao-Seed

**集成详情**: `integration-detail(integration_slug_id="integration-doubao-seed")`

**调用示例**:
```typescript
import { getDoubaoResponse } from '@/utils/llm';

async function getDivination(guaName: string) {
  const prompt = generateDivinationPrompt(guaName);
  const response = await getDoubaoResponse(prompt, {
    temperature: 0.7,
    maxTokens: 500
  });
  return response;
}
```

### 流式输出

所有AI功能都支持流式输出:

```typescript
async function streamDivination(prompt: string, onChunk: (chunk: string) => void) {
  const response = await fetch('/api/llm/stream', {
    method: 'POST',
    body: JSON.stringify({ prompt })
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    const chunk = decoder.decode(value);
    onChunk(chunk);
  }
}
```

## 关键代码位置

### 占卜组件

**文件**: `src/components/BirdDivination.tsx`

```typescript
export function BirdDivination() {
  const [gua, setGua] = useState<GuaCard | null>(null);
  const [interpretation, setInterpretation] = useState<string>("");
  const [remainingCount, setRemainingCount] = useState<number>(0);

  const handleDivination = async () => {
    // 调用API占卜
    // 更新状态
    // 显示结果
  };

  return (
    // 占卜UI
  );
}
```

### 预测组件

**文件**: `src/components/BirdPrediction.tsx`

```typescript
export function BirdPrediction() {
  const [question, setQuestion] = useState<string>("");
  const [prediction, setPrediction] = useState<string>("");

  const handlePrediction = async () => {
    // 调用API预测
  };

  return (
    // 预测UI
  );
}
```

### 人缘组件

**文件**: `src/app/affinity/page.tsx`

```typescript
export function BirdAffinity() {
  const [analysis, setAnalysis] = useState<string>("");

  const handleAffinity = async () => {
    // 调用API分析
  };

  return (
    // 人缘UI
  );
}
```

## 扩展功能建议

### 1. 历史记录

保存每次占卜/预测/人缘的结果:

```typescript
export const divinationHistory = pgTable("divination_history", {
  id: varchar("id", { length: 36 }).primaryKey(),
  userId: varchar("user_id", { length: 36 }).notNull(),
  guaId: int().notNull(),
  interpretation: text().notNull(),
  createdAt: timestamp("created_at", { withTimezone: true }).defaultNow(),
});
```

### 2. 命盘系统

生成个人命盘,长期追踪运势:

```typescript
export const natalChart = pgTable("natal_charts", {
  id: varchar("id", { length: 36 }).primaryKey(),
  userId: varchar("user_id", { length: 36 }).unique().notNull(),
  birthDate: timestamp("birth_date", { withTimezone: true }).notNull(),
  elements: jsonb().notNull(), // 五行属性
  luckyColor: varchar("lucky_color", { length: 20 }).notNull(),
  luckyNumber: int().notNull(),
  // ... 更多命盘信息
});
```

### 3. 社区占卜

用户可以分享自己的占卜结果:

```typescript
export const sharedDivinations = pgTable("shared_divinations", {
  id: varchar("id", { length: 36 }).primaryKey(),
  userId: varchar("user_id", { length: 36 }).notNull(),
  guaId: int().notNull(),
  interpretation: text().notNull(),
  likes: int().default(0),
  createdAt: timestamp("created_at", { withTimezone: true }).defaultNow(),
});
```

### 4. 专属AI人格

根据用户行为训练专属AI:

```typescript
export const aiPersonality = pgTable("ai_personality", {
  id: varchar("id", { length: 36 }).primaryKey(),
  userId: varchar("user_id", { length: 36 }).unique().notNull(),
  personality: jsonb().notNull(), // 人格特征
  memories: jsonb().notNull(), // 对话记忆
  updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow(),
});
```

## 常见问题

### Q1: 次数用完了怎么办?

A: 有以下方式获得额外次数:
1. 等待第二天自动重置
2. 成为会员获得额外次数
3. 完成打坐任务解锁1次

### Q2: 如何提高预测准确度?

A: 提供更详细的信息:
- 当前境界和关卡
- 具体的问题描述
- 相关的背景信息

### Q3: 卦象是随机的吗?

A: 是完全随机的,每个卦象概率均等(1/64)。

### Q4: AI解读的格式可以自定义吗?

A: 可以修改提示词模板,调整返回格式和内容。

## 维护记录

- 2026-01-19: 完善占卜、预测、人缘系统文档
- 2026-01-19: 添加打坐解锁机制
- 2026-01-19: 统一使用大语言模型集成


收藏

扫描二维码,在手机上阅读
文章目录


    呆鸟修仙 好友系统

    本文档详细说明游戏系统的核心玩法、关卡机制和数据逻辑。

    评 论
    评论已关闭