war-web/.cursorrules
2025-08-21 12:58:48 +08:00

252 lines
7.9 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# War-Web 红蓝攻防对抗系统 Cursor Rules
You are an expert full-stack developer working on the War-Web project, a 3D red-blue military confrontation simulation system. This project uses Vue 3 + TypeScript + Cesium.js for frontend and Python FastAPI for backend.
## 项目概述
- **项目名称**: War-Web (红蓝攻防对抗系统)
- **前端**: Vue 3 + TypeScript + Cesium.js + Element Plus + Pinia
- **后端**: Python FastAPI + PostgreSQL + Redis + WebSocket
- **核心功能**: 3D态势显示、实体管理、任务规划、态势感知、战况评估
## 代码规范与最佳实践
### 通用规范
- 使用英文注释和变量命名
- 采用语义化命名,清楚表达功能意图
- 每个文件必须有头部注释说明文件作用
- 重要函数必须添加完整的类型注解和文档字符串
- 实现完整的错误处理,避免静默失败
- 添加详细日志记录便于调试
### 前端开发规范 (Vue 3 + TypeScript + Cesium)
#### 文件结构约定
```
src/
├── api/ # API接口封装
├── cesium/ # Cesium核心类和管理器
├── components/ # Vue组件
│ ├── common/ # 通用组件
│ ├── cesium/ # Cesium相关组件
│ └── ui/ # UI组件
├── stores/ # Pinia状态管理
├── types/ # TypeScript类型定义
├── utils/ # 工具函数
└── views/ # 页面组件
```
#### Vue组件规范
- 使用Composition API + `<script setup>`
- 组件名使用PascalCase
- Props和Emits必须定义TypeScript类型
- 使用Element Plus组件库
- CSS使用scoped样式类名采用BEM命名
#### TypeScript类型定义
```typescript
// types/entities.ts - 实体相关类型
export interface Entity {
id: string
name: string
type: 'fighter' | 'drone' | 'missile'
side: 'red' | 'blue'
position: Position3D
status: EntityStatus
attributes: EntityAttributes
createdAt: string
}
export interface Position3D {
lng: number
lat: number
alt: number
}
export type EntityStatus = 'active' | 'damaged' | 'destroyed' | 'offline'
```
#### Cesium开发规范
- 为每个Cesium功能创建独立的Manager类
- 实体渲染使用EntityManager统一管理
- 航线规划使用FlightPathManager处理
- 地形和影像使用TerrainManager管理
- 实现资源清理和内存管理
```typescript
// cesium/EntityManager.ts
export class EntityManager {
private viewer: Cesium.Viewer
private entities: Map<string, Cesium.Entity> = new Map()
constructor(viewer: Cesium.Viewer) {
this.viewer = viewer
}
addEntity(entityData: Entity): Cesium.Entity {
// 实现实体添加逻辑
}
updateEntity(id: string, updates: Partial<Entity>): void {
// 实现实体更新逻辑
}
removeEntity(id: string): void {
// 实现实体移除逻辑,注意清理资源
}
}
```
#### Pinia状态管理规范
- 每个功能模块创建独立的store
- 使用TypeScript定义store类型
- Actions使用async/await处理异步操作
- 实现错误状态管理
```typescript
// stores/entities.ts
export const useEntitiesStore = defineStore('entities', () => {
const entities = ref<Entity[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const fetchEntities = async (): Promise<void> => {
loading.value = true
error.value = null
try {
const response = await entitiesApi.getAll()
entities.value = response.data
} catch (err) {
error.value = err instanceof Error ? err.message : '获取实体列表失败'
throw err
} finally {
loading.value = false
}
}
return {
entities: readonly(entities),
loading: readonly(loading),
error: readonly(error),
fetchEntities
}
})
```
### 后端开发规范 (Python FastAPI)
#### 项目结构
```
backend/
├── app/
│ ├── api/ # API路由
│ ├── core/ # 核心配置
│ ├── models/ # 数据模型
│ ├── schemas/ # Pydantic模式
│ ├── services/ # 业务逻辑
│ └── utils/ # 工具函数
├── alembic/ # 数据库迁移
└── tests/ # 测试文件
```
#### FastAPI开发规范
- 使用Pydantic进行数据验证
- 路由按功能模块分组
- 实现统一的错误处理
- 添加API文档和类型注解
```python
# schemas/entities.py
from pydantic import BaseModel, Field
from typing import Optional, Literal
from datetime import datetime
class Position3D(BaseModel):
lng: float = Field(..., ge=-180, le=180, description="经度")
lat: float = Field(..., ge=-90, le=90, description="纬度")
alt: float = Field(..., ge=0, description="高度(米)")
class EntityCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=50)
type: Literal["fighter", "drone", "missile"]
side: Literal["red", "blue"]
position: Position3D
attributes: Optional[dict] = Field(default_factory=dict)
class EntityResponse(EntityCreate):
id: str
status: str
created_at: datetime
class Config:
from_attributes = True
```
#### WebSocket实时通信
- 使用连接管理器管理WebSocket连接
- 实现分房间的消息广播
- 添加连接状态监控和重连机制
```python
# websocket/manager.py
class ConnectionManager:
def __init__(self):
self.active_connections: Dict[str, List[WebSocket]] = {}
async def connect(self, websocket: WebSocket, mission_id: str):
await websocket.accept()
if mission_id not in self.active_connections:
self.active_connections[mission_id] = []
self.active_connections[mission_id].append(websocket)
async def broadcast_to_mission(self, mission_id: str, message: dict):
if mission_id in self.active_connections:
for connection in self.active_connections[mission_id]:
try:
await connection.send_json(message)
except ConnectionClosedOK:
self.active_connections[mission_id].remove(connection)
```
## 开发指导原则
### 前端开发
1. **组件设计**: 遵循单一职责原则,保持组件简洁
2. **状态管理**: 合理使用Pinia避免过度设计
3. **性能优化**:
- Cesium实体使用LOD和可见性优化
- 虚拟滚动处理大量数据
- 懒加载和代码分割
4. **错误处理**: 实现全局错误捕获和用户友好的错误提示
5. **可访问性**: 提供键盘导航和屏幕阅读器支持
### 后端开发
1. **API设计**: 遵循RESTful规范使用合适的HTTP状态码
2. **数据验证**: 使用Pydantic进行严格的输入验证
3. **安全性**: 实现认证授权、输入过滤、SQL注入防护
4. **性能**: 使用异步编程、数据库连接池、缓存策略
5. **可监控性**: 添加详细日志、性能指标、健康检查
### 军事特定功能
1. **实体建模**: 准确建模军事实体的属性和行为
2. **坐标系统**: 使用标准军用坐标系统和地理参考
3. **实时性**: 确保态势数据的实时性和准确性
4. **兵推逻辑**: 实现真实的战术和策略逻辑
5. **数据安全**: 处理敏感军事数据的安全性
### 代码示例要求
当生成代码时,请:
- 包含完整的类型注解
- 添加详细的注释说明
- 实现错误处理逻辑
- 遵循项目的文件结构和命名规范
- 考虑性能和可维护性
- 为复杂逻辑提供单元测试示例
### 特定场景处理
- **大量实体渲染**: 使用Cesium的批量渲染和LOD技术
- **实时数据更新**: 优化WebSocket消息处理和状态同步
- **复杂航线规划**: 实现路径规划算法和碰撞检测
- **3D模型优化**: 使用合适的模型格式和压缩技术
- **跨平台兼容**: 确保在不同浏览器和设备上的兼容性
Remember: This is a military simulation system for training purposes only. Focus on creating realistic, performant, and maintainable code that serves educational and training objectives.