mirror of
https://github.com/setube/ogame-vue-ts.git
synced 2026-05-12 16:05:12 +08:00
Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80071ef0f6 | ||
|
|
d8dd4e7317 | ||
|
|
15eccd8f0d | ||
|
|
d4f55f6916 | ||
|
|
2cfa275c7a | ||
|
|
b1cf0acaae | ||
|
|
8f29a63756 | ||
|
|
a8ab2b0f1a | ||
|
|
28c3da2582 | ||
|
|
b0a7b5ce90 | ||
|
|
bd46c24824 | ||
|
|
8e49998205 | ||
|
|
703563c9b2 | ||
|
|
d44ea60ae9 | ||
|
|
1fc807915f | ||
|
|
bd6c474913 | ||
|
|
66c0ed8d0e | ||
|
|
9634dcb023 | ||
|
|
e4c4cdd63c | ||
|
|
7279bcbc89 | ||
|
|
d9c708e0ca | ||
|
|
21cf5762d2 | ||
|
|
8db70ea674 | ||
|
|
136591a3dd | ||
|
|
72f37aa435 | ||
|
|
4c54e1b773 | ||
|
|
9e8ceb0414 |
31
.dockerignore
Normal file
31
.dockerignore
Normal file
@@ -0,0 +1,31 @@
|
||||
# 排除不需要的文件和目录,减少 Docker 构建上下文大小
|
||||
|
||||
# 开发工具
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Git
|
||||
.git/
|
||||
.gitignore
|
||||
|
||||
# 构建产物(本地构建时会重新生成)
|
||||
docs/
|
||||
pkg/
|
||||
|
||||
# 临时文件
|
||||
*.tmp
|
||||
*.temp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# CI 相关文件
|
||||
.github/
|
||||
Dockerfile.ci
|
||||
|
||||
# 其他不需要的目录
|
||||
android/app/build/
|
||||
android/.gradle/
|
||||
resources/
|
||||
electron/dist/
|
||||
38
.dockerignore.ci
Normal file
38
.dockerignore.ci
Normal file
@@ -0,0 +1,38 @@
|
||||
# CI 构建专用的 dockerignore
|
||||
# 只保留构建产物和必要的配置文件
|
||||
|
||||
# 排除所有源代码和开发文件
|
||||
src/
|
||||
public/
|
||||
electron/
|
||||
node_modules/
|
||||
.vscode/
|
||||
.idea/
|
||||
.git/
|
||||
.github/
|
||||
|
||||
# 排除构建工具配置
|
||||
vite.config.ts
|
||||
tsconfig*.json
|
||||
*.config.js
|
||||
*.config.ts
|
||||
package.json
|
||||
package-lock.json
|
||||
pnpm-lock.yaml
|
||||
|
||||
# 排除其他构建产物
|
||||
pkg/
|
||||
android/
|
||||
resources/
|
||||
|
||||
# 排除临时文件
|
||||
*.tmp
|
||||
*.temp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.log
|
||||
|
||||
# 只保留以下文件:
|
||||
# - docs/ (构建产物)
|
||||
# - nginx.conf (nginx配置)
|
||||
# - Dockerfile.ci
|
||||
15
.github/FUNDING.yml
vendored
Normal file
15
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: ['https://afdian.com/a/setube'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
32
.github/workflows/build.yml
vendored
32
.github/workflows/build.yml
vendored
@@ -23,12 +23,12 @@ jobs:
|
||||
goarch: arm64
|
||||
executable: OGame-Vue-Ts-server-linux-arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 8
|
||||
version: latest
|
||||
- name: Setup Node & Go
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
@@ -55,17 +55,17 @@ jobs:
|
||||
name: Build Android APK
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 8
|
||||
version: latest
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '21'
|
||||
@@ -136,18 +136,18 @@ jobs:
|
||||
- os: ubuntu-latest
|
||||
platform: linux
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 8
|
||||
version: latest
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Cache Electron Builder
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.cache/electron
|
||||
@@ -180,7 +180,7 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Get Version
|
||||
id: get_version
|
||||
@@ -226,7 +226,7 @@ jobs:
|
||||
|
||||
# 4. 一次性上传,禁止重复匹配
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.get_version.outputs.VERSION }}
|
||||
name: Release ${{ steps.get_version.outputs.VERSION }}
|
||||
|
||||
35
.github/workflows/github-pages.yml
vendored
35
.github/workflows/github-pages.yml
vendored
@@ -19,21 +19,45 @@ jobs:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: 安装 pnpm
|
||||
- name: 设置 pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: latest
|
||||
|
||||
- name: 安装 Nodejs
|
||||
- name: 设置 Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
node-version: '20'
|
||||
|
||||
- name: 缓存 pnpm 依赖
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.pnpm-store
|
||||
node_modules
|
||||
key: ${{ runner.os }}-pnpm-pages-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-pages-
|
||||
|
||||
- name: 安装依赖
|
||||
run: pnpm install
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: 构建前端项目
|
||||
run: pnpm run build
|
||||
|
||||
- name: 验证构建产物
|
||||
run: |
|
||||
if [ ! -d "docs" ]; then
|
||||
echo "❌ 构建失败:docs 目录不存在"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -f "docs/index.html" ]; then
|
||||
echo "❌ 构建失败:docs/index.html 不存在"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ 构建产物验证通过"
|
||||
ls -la docs/
|
||||
|
||||
# 关键步骤:告诉 GitHub Actions 跳过 Jekyll 检查
|
||||
- name: 配置 Github Pages
|
||||
uses: actions/configure-pages@v5
|
||||
@@ -44,4 +68,5 @@ jobs:
|
||||
path: './docs'
|
||||
|
||||
- name: 部署到 GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
|
||||
131
.github/workflows/ogame-vue-ts.yml
vendored
131
.github/workflows/ogame-vue-ts.yml
vendored
@@ -1,4 +1,4 @@
|
||||
name: Docker 多架构构建并发布
|
||||
name: 构建并发布 Docker 镜像
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -15,10 +15,113 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# 设置 Node.js 环境
|
||||
- name: 设置 Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
# 设置 pnpm
|
||||
- name: 设置 pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: latest
|
||||
|
||||
# 缓存 pnpm 依赖
|
||||
- name: 缓存 pnpm 依赖
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.pnpm-store
|
||||
node_modules
|
||||
key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-
|
||||
|
||||
# 安装依赖
|
||||
- name: 安装依赖
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
# 构建项目
|
||||
- name: 构建项目
|
||||
run: pnpm run build
|
||||
|
||||
# 验证构建产物
|
||||
- name: 验证构建产物
|
||||
run: |
|
||||
if [ ! -d "docs" ]; then
|
||||
echo "❌ 构建失败:docs 目录不存在"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -f "docs/index.html" ]; then
|
||||
echo "❌ 构建失败:docs/index.html 不存在"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 检查构建产物的时间戳,确保是最新的
|
||||
BUILD_TIME=$(stat -c %Y docs/index.html 2>/dev/null || stat -f %m docs/index.html 2>/dev/null || echo "0")
|
||||
CURRENT_TIME=$(date +%s)
|
||||
TIME_DIFF=$((CURRENT_TIME - BUILD_TIME))
|
||||
|
||||
echo "📊 构建产物信息:"
|
||||
echo " 构建时间: $(date -d @$BUILD_TIME 2>/dev/null || date -r $BUILD_TIME 2>/dev/null || echo '未知')"
|
||||
echo " 当前时间: $(date)"
|
||||
echo " 时间差: ${TIME_DIFF}秒"
|
||||
|
||||
if [ $TIME_DIFF -gt 300 ]; then
|
||||
echo "⚠️ 警告: 构建产物可能不是最新的(超过5分钟)"
|
||||
fi
|
||||
|
||||
echo "✅ 构建产物验证通过"
|
||||
ls -la docs/
|
||||
|
||||
# 获取当前日期
|
||||
- name: 获取当前日期
|
||||
id: date
|
||||
run: echo "date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
|
||||
|
||||
# 获取版本号
|
||||
- name: 获取版本号
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "📦 当前版本: $VERSION"
|
||||
|
||||
# 准备 CI 构建环境
|
||||
- name: 准备 CI 构建环境
|
||||
run: |
|
||||
# 使用 CI 专用的 dockerignore
|
||||
cp .dockerignore.ci .dockerignore
|
||||
echo "✅ 已切换到 CI 构建模式"
|
||||
echo "📁 当前构建上下文文件:"
|
||||
ls -la | grep -E "(docs|nginx.conf|Dockerfile.ci|\.dockerignore)$"
|
||||
|
||||
# 清理可能冲突的镜像标签
|
||||
- name: 清理可能冲突的镜像标签
|
||||
continue-on-error: true
|
||||
run: |
|
||||
VERSION="${{ steps.version.outputs.version }}"
|
||||
echo "🧹 尝试清理可能冲突的镜像标签..."
|
||||
|
||||
# 尝试删除 GHCR 中的现有标签(如果存在)
|
||||
echo "清理 GHCR 标签..."
|
||||
docker buildx imagetools inspect ghcr.io/${{ github.repository_owner }}/ogame-vue-ts:$VERSION 2>/dev/null && \
|
||||
echo "发现现有版本标签,将被覆盖" || echo "版本标签不存在,可以安全推送"
|
||||
|
||||
# 如果配置了 Docker Hub,也尝试检查
|
||||
if [ -n "${{ vars.DOCKERHUB_USERNAME }}" ]; then
|
||||
echo "检查 Docker Hub 标签..."
|
||||
docker buildx imagetools inspect ${{ vars.DOCKERHUB_USERNAME }}/ogame-vue-ts:$VERSION 2>/dev/null && \
|
||||
echo "发现现有 Docker Hub 版本标签,将被覆盖" || echo "Docker Hub 版本标签不存在,可以安全推送"
|
||||
fi
|
||||
|
||||
echo "✅ 标签冲突检查完成,构建将覆盖任何现有标签"
|
||||
|
||||
# QEMU 用于支持多架构构建(必须)
|
||||
- name: 设置 QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
@@ -43,18 +146,34 @@ jobs:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
# 真正一键构建 + 推送多架构镜像(amd64 + arm64)
|
||||
# 构建并推送多架构镜像(使用构建产物)
|
||||
- name: 构建并推送多架构镜像
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.ci
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
no-cache: false
|
||||
pull: true
|
||||
tags: |
|
||||
ghcr.io/${{ github.repository_owner }}/ogame-vue-ts:latest
|
||||
ghcr.io/${{ github.repository_owner }}/ogame-vue-ts:${{ steps.version.outputs.version }}
|
||||
ghcr.io/${{ github.repository_owner }}/ogame-vue-ts:${{ github.sha }}
|
||||
${{ vars.DOCKERHUB_USERNAME != '' && format('docker.io/{0}/ogame-vue-ts:latest', vars.DOCKERHUB_USERNAME) || '' }}
|
||||
${{ vars.DOCKERHUB_USERNAME != '' && format('docker.io/{0}/ogame-vue-ts:{1}', vars.DOCKERHUB_USERNAME, github.sha) || '' }}
|
||||
${{ vars.DOCKERHUB_USERNAME && format('{0}/ogame-vue-ts:latest', vars.DOCKERHUB_USERNAME) || '' }}
|
||||
${{ vars.DOCKERHUB_USERNAME && format('{0}/ogame-vue-ts:{1}', vars.DOCKERHUB_USERNAME, steps.version.outputs.version) || '' }}
|
||||
${{ vars.DOCKERHUB_USERNAME && format('{0}/ogame-vue-ts:{1}', vars.DOCKERHUB_USERNAME, github.sha) || '' }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
outputs: type=image,name=target,annotation-index.org.opencontainers.image.description=OGame Vue Ts
|
||||
build-args: |
|
||||
BUILDKIT_INLINE_CACHE=1
|
||||
BUILD_DATE=${{ steps.date.outputs.date }}
|
||||
VERSION=${{ steps.version.outputs.version }}
|
||||
COMMIT_SHA=${{ github.sha }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=OGame Vue Ts
|
||||
org.opencontainers.image.description=OGame Vue TypeScript Implementation
|
||||
org.opencontainers.image.version=${{ steps.version.outputs.version }}
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
org.opencontainers.image.revision=${{ github.sha }}
|
||||
org.opencontainers.image.created=${{ steps.date.outputs.date }}
|
||||
|
||||
89
DOCKER.md
Normal file
89
DOCKER.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# Docker 构建说明
|
||||
|
||||
本项目支持两种 Docker 构建方式:
|
||||
|
||||
## 🏠 本地构建
|
||||
|
||||
### 方式一:使用构建脚本(推荐)
|
||||
|
||||
**Linux/macOS:**
|
||||
```bash
|
||||
chmod +x build-docker.sh
|
||||
./build-docker.sh
|
||||
```
|
||||
|
||||
**Windows:**
|
||||
```cmd
|
||||
build-docker.bat
|
||||
```
|
||||
|
||||
### 方式二:直接使用 Docker 命令
|
||||
|
||||
```bash
|
||||
# 构建镜像
|
||||
docker build -t ogame-vue-ts:local .
|
||||
|
||||
# 运行容器
|
||||
docker run -p 8080:80 ogame-vue-ts:local
|
||||
```
|
||||
|
||||
## ☁️ GitHub Actions 自动构建
|
||||
|
||||
当代码推送到 `main` 分支或创建 tag 时,GitHub Actions 会自动:
|
||||
|
||||
1. 在 Actions 环境中构建项目
|
||||
2. 使用构建产物创建 Docker 镜像
|
||||
3. 推送到 GitHub Container Registry 和 Docker Hub
|
||||
|
||||
### 使用预构建镜像
|
||||
|
||||
```bash
|
||||
# 从 GitHub Container Registry 拉取
|
||||
docker pull ghcr.io/your-username/ogame-vue-ts:latest
|
||||
|
||||
# 从 Docker Hub 拉取(如果配置了)
|
||||
docker pull your-dockerhub-username/ogame-vue-ts:latest
|
||||
|
||||
# 运行
|
||||
docker run -p 8080:80 ghcr.io/your-username/ogame-vue-ts:latest
|
||||
```
|
||||
|
||||
## 📁 文件说明
|
||||
|
||||
- `Dockerfile` - 本地构建用,包含完整的源代码构建流程
|
||||
- `Dockerfile.ci` - GitHub Actions 构建用,使用预构建产物
|
||||
- `.dockerignore` - 本地构建时排除的文件
|
||||
- `.dockerignore.ci` - CI 构建时排除的文件
|
||||
- `build-docker.sh` / `build-docker.bat` - 本地构建便捷脚本
|
||||
|
||||
## 🔧 配置说明
|
||||
|
||||
### GitHub Actions 环境变量
|
||||
|
||||
需要在 GitHub 仓库设置中配置:
|
||||
|
||||
**Variables (公开):**
|
||||
- `DOCKERHUB_USERNAME` - Docker Hub 用户名(可选)
|
||||
|
||||
**Secrets (私密):**
|
||||
- `DOCKERHUB_TOKEN` - Docker Hub 访问令牌(可选)
|
||||
- `GITHUB_TOKEN` - 自动提供,用于 GHCR
|
||||
|
||||
### 本地构建要求
|
||||
|
||||
- Docker
|
||||
- 足够的磁盘空间(构建过程中会下载 Node.js 依赖)
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
1. **本地开发测试:**
|
||||
```bash
|
||||
./build-docker.sh
|
||||
docker run -p 8080:80 ogame-vue-ts:local
|
||||
```
|
||||
|
||||
2. **访问应用:**
|
||||
打开浏览器访问 `http://localhost:8080`
|
||||
|
||||
3. **生产部署:**
|
||||
使用 GitHub Actions 自动构建的镜像进行部署
|
||||
38
Dockerfile
38
Dockerfile
@@ -1,22 +1,40 @@
|
||||
FROM node:lts-alpine AS builder
|
||||
# 本地构建用的 Dockerfile
|
||||
# 支持完整的源代码构建流程
|
||||
|
||||
RUN mkdir -p /workspace
|
||||
WORKDIR /workspace
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
|
||||
RUN apk update && apk add git
|
||||
RUN npm config set registry https://registry.npmmirror.com
|
||||
RUN git clone https://github.com/setube/ogame-vue-ts.git
|
||||
RUN mv ./ogame-vue-ts/* . ; rm -rf ./ogame-vue-ts/
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
RUN npm install -g pnpm ; pnpm install;
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 复制 package 文件
|
||||
COPY package.json pnpm-lock.yaml ./
|
||||
|
||||
# 安装 pnpm
|
||||
RUN npm install -g pnpm
|
||||
|
||||
# 安装依赖
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
# 复制源代码
|
||||
COPY . .
|
||||
|
||||
# 构建项目
|
||||
RUN pnpm run build
|
||||
|
||||
# 生产阶段
|
||||
FROM nginx:alpine
|
||||
|
||||
# 复制 nginx 配置文件
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
# 清理默认的 nginx 静态文件
|
||||
RUN rm -rf /usr/share/nginx/html/*
|
||||
COPY --from=builder /workspace/docs /usr/share/nginx/html
|
||||
|
||||
# 复制构建产物到 nginx 静态文件目录
|
||||
COPY --from=builder /app/docs /usr/share/nginx/html
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 80
|
||||
|
||||
# 启动 nginx
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
35
Dockerfile.ci
Normal file
35
Dockerfile.ci
Normal file
@@ -0,0 +1,35 @@
|
||||
# GitHub Actions 构建用的 Dockerfile
|
||||
# 使用预构建的产物,不包含源代码构建过程
|
||||
|
||||
FROM nginx:alpine
|
||||
|
||||
# 添加构建参数用于缓存破坏
|
||||
ARG BUILD_DATE
|
||||
ARG VERSION
|
||||
ARG COMMIT_SHA
|
||||
|
||||
# 添加标签信息
|
||||
LABEL build.date="${BUILD_DATE}" \
|
||||
build.version="${VERSION}" \
|
||||
build.commit="${COMMIT_SHA}"
|
||||
|
||||
# 复制 nginx 配置文件
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
# 清理默认的 nginx 静态文件
|
||||
RUN rm -rf /usr/share/nginx/html/*
|
||||
|
||||
# 复制构建产物到 nginx 静态文件目录
|
||||
# 这里的 docs 目录是在 GitHub Actions 中构建生成的
|
||||
# 使用 --chown 确保正确的文件权限
|
||||
COPY --chown=nginx:nginx docs /usr/share/nginx/html
|
||||
|
||||
# 验证构建产物
|
||||
RUN ls -la /usr/share/nginx/html/ && \
|
||||
test -f /usr/share/nginx/html/index.html || (echo "构建产物验证失败" && exit 1)
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 80
|
||||
|
||||
# 启动 nginx
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -10,6 +10,7 @@
|
||||
android:usesCleartextTraffic="true"
|
||||
android:hardwareAccelerated="true"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:requestLegacyExternalStorage="true"
|
||||
android:theme="@style/AppTheme">
|
||||
|
||||
<activity
|
||||
@@ -41,6 +42,18 @@
|
||||
<!-- Permissions -->
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
|
||||
<!-- 旧版本存储权限 (Android 10 及以下) -->
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="30" />
|
||||
|
||||
<!-- Android 11+ (API 30+) 完整外部存储访问权限 -->
|
||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
|
||||
|
||||
<!-- Android 13+ (API 33+) 细粒度媒体权限 -->
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
|
||||
</manifest>
|
||||
@@ -8,9 +8,12 @@ import android.os.Bundle;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.view.animation.AccelerateDecelerateInterpolator;
|
||||
import android.webkit.ValueCallback;
|
||||
import android.webkit.WebChromeClient;
|
||||
import android.webkit.WebSettings;
|
||||
import android.webkit.WebView;
|
||||
import android.net.Uri;
|
||||
import android.content.Intent;
|
||||
import androidx.core.splashscreen.SplashScreen;
|
||||
import androidx.core.view.WindowCompat;
|
||||
import androidx.core.view.WindowInsetsControllerCompat;
|
||||
@@ -18,6 +21,8 @@ import com.getcapacitor.BridgeActivity;
|
||||
|
||||
public class MainActivity extends BridgeActivity {
|
||||
private boolean isWebViewReady = false;
|
||||
private static final int FILE_CHOOSER_REQUEST_CODE = 1001;
|
||||
private ValueCallback<Uri[]> filePathCallback;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
@@ -94,7 +99,50 @@ public class MainActivity extends BridgeActivity {
|
||||
isWebViewReady = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
|
||||
FileChooserParams fileChooserParams) {
|
||||
// 清理之前的回调
|
||||
if (MainActivity.this.filePathCallback != null) {
|
||||
MainActivity.this.filePathCallback.onReceiveValue(null);
|
||||
}
|
||||
|
||||
MainActivity.this.filePathCallback = filePathCallback;
|
||||
|
||||
// 创建文件选择器 Intent
|
||||
Intent intent = fileChooserParams.createIntent();
|
||||
try {
|
||||
startActivityForResult(intent, FILE_CHOOSER_REQUEST_CODE);
|
||||
} catch (android.content.ActivityNotFoundException e) {
|
||||
MainActivity.this.filePathCallback = null;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
|
||||
if (requestCode == FILE_CHOOSER_REQUEST_CODE) {
|
||||
if (filePathCallback == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Uri[] results = null;
|
||||
if (resultCode == RESULT_OK && data != null) {
|
||||
String dataString = data.getDataString();
|
||||
if (dataString != null) {
|
||||
results = new Uri[]{Uri.parse(dataString)};
|
||||
}
|
||||
}
|
||||
|
||||
filePathCallback.onReceiveValue(results);
|
||||
filePathCallback = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
17
build-docker.bat
Normal file
17
build-docker.bat
Normal file
@@ -0,0 +1,17 @@
|
||||
@echo off
|
||||
REM 本地 Docker 构建脚本 (Windows)
|
||||
REM 使用完整的源代码构建流程
|
||||
|
||||
echo 🚀 开始本地 Docker 构建...
|
||||
|
||||
REM 构建镜像
|
||||
docker build -t ogame-vue-ts:local .
|
||||
|
||||
if %ERRORLEVEL% EQU 0 (
|
||||
echo ✅ Docker 镜像构建成功!
|
||||
echo 📦 镜像标签: ogame-vue-ts:local
|
||||
echo 🏃 运行命令: docker run -p 8080:80 ogame-vue-ts:local
|
||||
) else (
|
||||
echo ❌ Docker 镜像构建失败!
|
||||
exit /b 1
|
||||
)
|
||||
18
build-docker.sh
Normal file
18
build-docker.sh
Normal file
@@ -0,0 +1,18 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 本地 Docker 构建脚本
|
||||
# 使用完整的源代码构建流程
|
||||
|
||||
echo "🚀 开始本地 Docker 构建..."
|
||||
|
||||
# 构建镜像
|
||||
docker build -t ogame-vue-ts:local .
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "✅ Docker 镜像构建成功!"
|
||||
echo "📦 镜像标签: ogame-vue-ts:local"
|
||||
echo "🏃 运行命令: docker run -p 8080:80 ogame-vue-ts:local"
|
||||
else
|
||||
echo "❌ Docker 镜像构建失败!"
|
||||
exit 1
|
||||
fi
|
||||
@@ -8,8 +8,8 @@
|
||||
"email": "1962257451@qq.com"
|
||||
},
|
||||
"private": true,
|
||||
"version": "1.6.0",
|
||||
"buildDate": "2026/1/6 03:05:21",
|
||||
"version": "1.6.5",
|
||||
"buildDate": "2026/1/23 02:22:24",
|
||||
"main": "dist-electron/main.js",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -82,7 +82,6 @@
|
||||
"electron"
|
||||
]
|
||||
},
|
||||
"packageManager": "pnpm@10.13.1+sha512.37ebf1a5c7a30d5fabe0c5df44ee8da4c965ca0c5af3dbab28c3a1681b70a256218d05c81c9c0dcf767ef6b8551eb5b960042b9ed4300c59242336377e01cfad",
|
||||
"build": {
|
||||
"appId": "games.wenzi.ogame",
|
||||
"productName": "OGame-Vue-Ts",
|
||||
|
||||
38
src/App.vue
38
src/App.vue
@@ -518,7 +518,7 @@
|
||||
import HintToast from '@/components/notifications/HintToast.vue'
|
||||
import BackToTop from '@/components/common/BackToTop.vue'
|
||||
import Sonner from '@/components/ui/sonner/Sonner.vue'
|
||||
import { MissionType, BuildingType, TechnologyType, DiplomaticEventType, ShipType } from '@/types/game'
|
||||
import { MissionType, BuildingType, TechnologyType, DiplomaticEventType, ShipType, DefenseType } from '@/types/game'
|
||||
import type { FleetMission, NPC, MissileAttack } from '@/types/game'
|
||||
import { DIPLOMATIC_CONFIG } from '@/config/gameConfig'
|
||||
import type { VersionInfo } from '@/utils/versionCheck'
|
||||
@@ -765,7 +765,7 @@
|
||||
return
|
||||
}
|
||||
|
||||
if (!settings.types[typeKey]) return
|
||||
if (!settings.types[typeKey as keyof typeof settings.types]) return
|
||||
|
||||
// 浏览器通知
|
||||
if (settings.browser && 'Notification' in window && Notification.permission === 'granted') {
|
||||
@@ -853,6 +853,29 @@
|
||||
generateNPCPlanets()
|
||||
}
|
||||
|
||||
// 数据迁移:为没有 bonusPoints 的玩家计算奖励积分
|
||||
if (gameStore.player.bonusPoints === undefined) {
|
||||
// 计算基础积分(建筑、科技、舰船、防御)
|
||||
let totalCost = 0
|
||||
gameStore.player.planets.forEach(planet => {
|
||||
Object.entries(planet.buildings).forEach(([buildingType, level]) => {
|
||||
totalCost += publicLogic.calculateBuildingTotalCost(buildingType as BuildingType, level)
|
||||
})
|
||||
Object.entries(planet.fleet).forEach(([shipType, count]) => {
|
||||
totalCost += publicLogic.calculateShipUnitCost(shipType as ShipType) * count
|
||||
})
|
||||
Object.entries(planet.defense).forEach(([defenseType, count]) => {
|
||||
totalCost += publicLogic.calculateDefenseUnitCost(defenseType as DefenseType) * count
|
||||
})
|
||||
})
|
||||
Object.entries(gameStore.player.technologies).forEach(([techType, level]) => {
|
||||
totalCost += publicLogic.calculateTechnologyTotalCost(techType as TechnologyType, level)
|
||||
})
|
||||
const basePoints = Math.floor(totalCost / 1000)
|
||||
// bonusPoints = 当前积分 - 基础积分
|
||||
gameStore.player.bonusPoints = Math.max(0, gameStore.player.points - basePoints)
|
||||
}
|
||||
|
||||
// 初始化或更新玩家积分
|
||||
gameStore.player.points = publicLogic.calculatePlayerPoints(gameStore.player)
|
||||
|
||||
@@ -1512,6 +1535,17 @@
|
||||
read: false
|
||||
})
|
||||
}
|
||||
|
||||
// 更新任务状态为返回中
|
||||
// Deploy任务不需要返回(舰队已经留在目标星球)
|
||||
if (mission.missionType !== MissionType.Deploy) {
|
||||
mission.status = 'returning'
|
||||
// 确保returnTime已设置(如果还没设置的话)
|
||||
if (!mission.returnTime) {
|
||||
const flightTime = mission.arrivalTime - mission.departureTime
|
||||
mission.returnTime = Date.now() + flightTime
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const processMissionReturn = (mission: FleetMission) => {
|
||||
|
||||
@@ -498,11 +498,7 @@
|
||||
|
||||
// 如果有星际研究网络,计算有效实验室等级
|
||||
if (intergalacticResearchNetworkLevel > 0) {
|
||||
return researchLogic.calculateEffectiveLabLevel(
|
||||
gameStore.player.planets,
|
||||
currentPlanet.value.id,
|
||||
intergalacticResearchNetworkLevel
|
||||
)
|
||||
return researchLogic.calculateEffectiveLabLevel(gameStore.player.planets, currentPlanet.value.id, intergalacticResearchNetworkLevel)
|
||||
}
|
||||
|
||||
return currentPlanet.value.buildings['researchLab'] || 0
|
||||
@@ -599,11 +595,7 @@
|
||||
const miningTechLevel = gameStore.player?.technologies?.[TechnologyType.MiningTechnology] || 0
|
||||
|
||||
// 使用增强版计算函数获取带加成的储量上限
|
||||
const enhancedDeposits = oreDepositLogic.calculateEnhancedDeposits(
|
||||
deposits.position,
|
||||
deepDrillingLevel,
|
||||
miningTechLevel
|
||||
)
|
||||
const enhancedDeposits = oreDepositLogic.calculateEnhancedDeposits(deposits.position, deepDrillingLevel, miningTechLevel)
|
||||
const initial = enhancedDeposits[resourceType]
|
||||
|
||||
// 百分比基于增强后的上限计算
|
||||
|
||||
@@ -538,12 +538,13 @@ export const TECHNOLOGIES: Record<TechnologyType, TechnologyConfig> = {
|
||||
baseTime: 60,
|
||||
costMultiplier: 2,
|
||||
fleetStorageBonus: 500, // 每级全局增加500舰队仓储
|
||||
maxLevel: 10, // 最多10级(最多11个研究队列和11个舰队槽位)
|
||||
maxLevel: 10, // 最多15级(最多16个研究队列和16个舰队槽位)
|
||||
requirements: { [BuildingType.ResearchLab]: 1 },
|
||||
levelRequirements: {
|
||||
3: { [BuildingType.ResearchLab]: 5 },
|
||||
5: { [BuildingType.ResearchLab]: 8, [BuildingType.RoboticsFactory]: 5 },
|
||||
8: { [BuildingType.ResearchLab]: 10, [BuildingType.NaniteFactory]: 2 }
|
||||
8: { [BuildingType.ResearchLab]: 10, [BuildingType.NaniteFactory]: 2 },
|
||||
12: { [BuildingType.ResearchLab]: 12, [BuildingType.NaniteFactory]: 5 }
|
||||
}
|
||||
},
|
||||
[TechnologyType.EspionageTechnology]: {
|
||||
@@ -777,7 +778,7 @@ export const TECHNOLOGIES: Record<TechnologyType, TechnologyConfig> = {
|
||||
},
|
||||
8: {
|
||||
[BuildingType.ResearchLab]: 14,
|
||||
[TechnologyType.ComputerTechnology]: 12,
|
||||
[TechnologyType.ComputerTechnology]: 10,
|
||||
[BuildingType.NaniteFactory]: 5
|
||||
}
|
||||
}
|
||||
@@ -1395,7 +1396,7 @@ export const MOON_CONFIG = {
|
||||
maxChance: 20, // 最大20%概率(需要2M残骸)
|
||||
chancePerDebris: 100000, // 每10万资源增加1%概率
|
||||
baseFields: 1, // 月球初始空间(OGame规则:初始只有1格)
|
||||
lunarBaseFieldsBonus: 3, // 每级月球基地增加的空间(每级+3格,占用1格,净增2格)
|
||||
lunarBaseFieldsBonus: 30, // 每级月球基地增加的空间(每级+30格,占用0格)
|
||||
minDiameter: 3476, // 最小月球直径(km),1%概率时
|
||||
maxDiameter: 8944, // 最大月球直径(km),20%概率时保证>8000km
|
||||
baseDiameter: 3000, // 基础直径(km)
|
||||
|
||||
@@ -960,6 +960,7 @@ export default {
|
||||
exporting: 'Exportieren...',
|
||||
exportSuccess: 'Export erfolgreich',
|
||||
exportSuccessWithPath: 'Export erfolgreich, Datei gespeichert unter: {path}',
|
||||
exportCopiedToClipboard: 'Export erfolgreich, Daten in die Zwischenablage kopiert',
|
||||
storagePermissionDenied: 'Speicherberechtigung verweigert, Datei kann nicht exportiert werden',
|
||||
exportFailed: 'Export fehlgeschlagen, bitte erneut versuchen',
|
||||
importData: 'Daten importieren',
|
||||
@@ -1084,6 +1085,20 @@ export default {
|
||||
},
|
||||
gmView: {
|
||||
title: 'GM-Kontrollpanel',
|
||||
presets: 'Vorlagen',
|
||||
choosePreset: 'Vorlage wählen',
|
||||
defaultPreset: 'Standardvorlage',
|
||||
applyPreset: 'Vorlage anwenden',
|
||||
savePreset: 'Vorlage speichern',
|
||||
presetName: 'Vorlagenname',
|
||||
presetNameRequired: 'Bitte geben Sie einen Namen ein',
|
||||
presetSaved: 'Vorlage gespeichert',
|
||||
presetApplied: 'Vorlage angewendet',
|
||||
deletePreset: 'Vorlage löschen',
|
||||
presetDeleted: 'Vorlage gelöscht',
|
||||
confirmOverwriteTitle: 'Vorlage existiert bereits',
|
||||
confirmOverwriteMessage: 'Eine Vorlage mit dem Namen "{name}" existiert bereits. Überschreiben?',
|
||||
cannotDeleteDefault: 'Standardvorlage kann nicht gelöscht werden',
|
||||
adminOnly: 'Nur Admin',
|
||||
selectPlanet: 'Planet auswählen',
|
||||
choosePlanet: 'Einen Planeten auswählen',
|
||||
@@ -1184,6 +1199,15 @@ export default {
|
||||
}
|
||||
},
|
||||
diplomacy: {
|
||||
sort: {
|
||||
label: 'Sortieren',
|
||||
ascending: 'Aufsteigend',
|
||||
descending: 'Absteigend',
|
||||
reputation: 'Ruf',
|
||||
planets: 'Planeten',
|
||||
difficulty: 'Schwierigkeit',
|
||||
allies: 'Verbündete'
|
||||
},
|
||||
title: 'Diplomatie',
|
||||
description: 'Verwalte diplomatische Beziehungen mit NPCs',
|
||||
tabs: {
|
||||
|
||||
@@ -978,6 +978,7 @@ export default {
|
||||
exporting: 'Exporting...',
|
||||
exportSuccess: 'Export successful',
|
||||
exportSuccessWithPath: 'Export successful, file saved to: {path}',
|
||||
exportCopiedToClipboard: 'Export successful, data copied to clipboard',
|
||||
storagePermissionDenied: 'Storage permission denied, cannot export file',
|
||||
exportFailed: 'Export failed, please try again',
|
||||
importData: 'Import Data',
|
||||
@@ -1100,6 +1101,20 @@ export default {
|
||||
},
|
||||
gmView: {
|
||||
title: 'GM Control Panel',
|
||||
presets: 'Presets',
|
||||
choosePreset: 'Choose Preset',
|
||||
defaultPreset: 'Default Preset',
|
||||
applyPreset: 'Apply Preset',
|
||||
savePreset: 'Save Preset',
|
||||
presetName: 'Preset Name',
|
||||
presetNameRequired: 'Please enter a preset name',
|
||||
presetSaved: 'Preset saved',
|
||||
presetApplied: 'Preset applied',
|
||||
deletePreset: 'Delete Preset',
|
||||
presetDeleted: 'Preset deleted',
|
||||
confirmOverwriteTitle: 'Preset Already Exists',
|
||||
confirmOverwriteMessage: 'Preset with name "{name}" already exists. Overwrite?',
|
||||
cannotDeleteDefault: 'Cannot delete default preset',
|
||||
adminOnly: 'Admin Only',
|
||||
selectPlanet: 'Select Planet',
|
||||
choosePlanet: 'Choose a planet',
|
||||
@@ -1290,6 +1305,15 @@ export default {
|
||||
npcEliminatedMessage: "You destroyed all of {npcName}'s planets! This faction has been completely wiped out."
|
||||
},
|
||||
searchPlaceholder: 'Search NPC name...',
|
||||
sort: {
|
||||
label: 'Sort',
|
||||
ascending: 'Ascending',
|
||||
descending: 'Descending',
|
||||
reputation: 'Reputation',
|
||||
planets: 'Planets',
|
||||
difficulty: 'Difficulty',
|
||||
allies: 'Allies'
|
||||
},
|
||||
// Notification types
|
||||
notificationType: {
|
||||
tradeOffer: 'Trade Offer',
|
||||
|
||||
@@ -969,6 +969,7 @@ export default {
|
||||
exporting: 'Exportando...',
|
||||
exportSuccess: 'Exportación exitosa',
|
||||
exportSuccessWithPath: 'Exportación exitosa, archivo guardado en: {path}',
|
||||
exportCopiedToClipboard: 'Exportación exitosa, datos copiados al portapapeles',
|
||||
storagePermissionDenied: 'Permiso de almacenamiento denegado, no se puede exportar el archivo',
|
||||
exportFailed: 'Exportación fallida, por favor intenta de nuevo',
|
||||
importData: 'Importar Datos',
|
||||
@@ -1092,6 +1093,20 @@ export default {
|
||||
},
|
||||
gmView: {
|
||||
title: 'Panel de Control GM',
|
||||
presets: 'Preajustes',
|
||||
choosePreset: 'Elegir preajuste',
|
||||
defaultPreset: 'Preajuste predeterminado',
|
||||
applyPreset: 'Aplicar preajuste',
|
||||
savePreset: 'Guardar preajuste',
|
||||
presetName: 'Nombre del preajuste',
|
||||
presetNameRequired: 'Ingrese el nombre del preajuste',
|
||||
presetSaved: 'Preajuste guardado',
|
||||
presetApplied: 'Preajuste aplicado',
|
||||
deletePreset: 'Eliminar preajuste',
|
||||
presetDeleted: 'Preajuste eliminado',
|
||||
confirmOverwriteTitle: 'El preajuste ya existe',
|
||||
confirmOverwriteMessage: 'El preajuste con el nombre "{name}" ya existe. ¿Sobrescribir?',
|
||||
cannotDeleteDefault: 'No se puede eliminar el preajuste predeterminado',
|
||||
adminOnly: 'Solo Administrador',
|
||||
selectPlanet: 'Seleccionar Planeta',
|
||||
choosePlanet: 'Elige un planeta',
|
||||
@@ -1192,6 +1207,15 @@ export default {
|
||||
}
|
||||
},
|
||||
diplomacy: {
|
||||
sort: {
|
||||
label: 'Ordenar',
|
||||
ascending: 'Ascendente',
|
||||
descending: 'Descendente',
|
||||
reputation: 'Reputación',
|
||||
planets: 'Planetas',
|
||||
difficulty: 'Dificultad',
|
||||
allies: 'Aliados'
|
||||
},
|
||||
title: 'Diplomacia',
|
||||
description: 'Gestionar relaciones diplomáticas con NPCs',
|
||||
tabs: {
|
||||
|
||||
@@ -983,6 +983,7 @@ export default {
|
||||
exporting: 'エクスポート中...',
|
||||
exportSuccess: 'エクスポート成功',
|
||||
exportSuccessWithPath: 'エクスポート成功、ファイルの保存先:{path}',
|
||||
exportCopiedToClipboard: 'エクスポート成功、データがクリップボードにコピーされました',
|
||||
storagePermissionDenied: 'ストレージ権限が拒否されました。ファイルをエクスポートできません',
|
||||
exportFailed: 'エクスポートに失敗しました。もう一度お試しください',
|
||||
importData: 'データインポート',
|
||||
@@ -1110,6 +1111,20 @@ export default {
|
||||
},
|
||||
gmView: {
|
||||
title: 'GMコントロールパネル',
|
||||
presets: 'プリセット',
|
||||
choosePreset: 'プリセット選択',
|
||||
defaultPreset: 'デフォルト',
|
||||
applyPreset: '適用',
|
||||
savePreset: '保存',
|
||||
presetName: 'プリセット名',
|
||||
presetNameRequired: 'プリセット名を入力してください',
|
||||
presetSaved: '保存しました',
|
||||
presetApplied: '適用しました',
|
||||
deletePreset: 'プリセット削除',
|
||||
presetDeleted: 'プリセットを削除しました',
|
||||
confirmOverwriteTitle: 'プリセットは既に存在します',
|
||||
confirmOverwriteMessage: 'プリセット名 "{name}" は既に存在します。上書きしますか?',
|
||||
cannotDeleteDefault: 'デフォルトプリセットは削除できません',
|
||||
adminOnly: '管理者専用',
|
||||
selectPlanet: '惑星を選択',
|
||||
choosePlanet: '惑星を選択してください',
|
||||
@@ -1209,6 +1224,15 @@ export default {
|
||||
}
|
||||
},
|
||||
diplomacy: {
|
||||
sort: {
|
||||
label: '並び替え',
|
||||
ascending: '昇順',
|
||||
descending: '降順',
|
||||
reputation: '評判',
|
||||
planets: '惑星',
|
||||
difficulty: '難易度',
|
||||
allies: '同盟'
|
||||
},
|
||||
title: '外交',
|
||||
description: 'NPCとの外交関係を管理',
|
||||
tabs: {
|
||||
|
||||
@@ -938,6 +938,7 @@ export default {
|
||||
exporting: '내보내는 중...',
|
||||
exportSuccess: '내보내기 성공',
|
||||
exportSuccessWithPath: '내보내기 성공, 파일 저장 위치: {path}',
|
||||
exportCopiedToClipboard: '내보내기 성공, 데이터가 클립보드에 복사됨',
|
||||
storagePermissionDenied: '저장소 권한이 거부되어 파일을 내보낼 수 없습니다',
|
||||
exportFailed: '내보내기 실패, 다시 시도해주세요',
|
||||
importData: '데이터 가져오기',
|
||||
@@ -1060,6 +1061,20 @@ export default {
|
||||
},
|
||||
gmView: {
|
||||
title: 'GM 제어판',
|
||||
presets: '프리셋',
|
||||
choosePreset: '프리셋 선택',
|
||||
defaultPreset: '기본 프리셋',
|
||||
applyPreset: '프리셋 적용',
|
||||
savePreset: '프리셋 저장',
|
||||
presetName: '프리셋 이름',
|
||||
presetNameRequired: '프리셋 이름을 입력하세요',
|
||||
presetSaved: '프리셋 저장됨',
|
||||
presetApplied: '프리셋 적용됨',
|
||||
deletePreset: '프리셋 삭제',
|
||||
presetDeleted: '프리셋 삭제됨',
|
||||
confirmOverwriteTitle: '프리셋이 이미 존재함',
|
||||
confirmOverwriteMessage: '"{name}" 이름의 프리셋이 이미 존재합니다. 덮어쓰시겠습니까?',
|
||||
cannotDeleteDefault: '기본 프리셋은 삭제할 수 없습니다',
|
||||
adminOnly: '관리자 전용',
|
||||
selectPlanet: '행성 선택',
|
||||
choosePlanet: '행성을 선택하세요',
|
||||
@@ -1159,6 +1174,15 @@ export default {
|
||||
}
|
||||
},
|
||||
diplomacy: {
|
||||
sort: {
|
||||
label: '정렬',
|
||||
ascending: '오름차순',
|
||||
descending: '내림차순',
|
||||
reputation: '평판',
|
||||
planets: '행성',
|
||||
difficulty: '난이도',
|
||||
allies: '동맹'
|
||||
},
|
||||
title: '외교',
|
||||
description: 'NPC와의 외교 관계 관리',
|
||||
tabs: {
|
||||
|
||||
@@ -961,6 +961,7 @@ export default {
|
||||
exporting: 'Экспорт...',
|
||||
exportSuccess: 'Экспорт успешен',
|
||||
exportSuccessWithPath: 'Экспорт успешен, файл сохранен в: {path}',
|
||||
exportCopiedToClipboard: 'Экспорт успешен, данные скопированы в буфер обмена',
|
||||
storagePermissionDenied: 'Разрешение на хранение отклонено, невозможно экспортировать файл',
|
||||
exportFailed: 'Экспорт не удался, попробуйте еще раз',
|
||||
importData: 'Импорт данных',
|
||||
@@ -1086,6 +1087,20 @@ export default {
|
||||
},
|
||||
gmView: {
|
||||
title: 'Панель управления GM',
|
||||
presets: 'Предустановки',
|
||||
choosePreset: 'Выбрать предустановку',
|
||||
defaultPreset: 'Стандартная',
|
||||
applyPreset: 'Применить',
|
||||
savePreset: 'Сохранить',
|
||||
presetName: 'Название',
|
||||
presetNameRequired: 'Введите название',
|
||||
presetSaved: 'Сохранено',
|
||||
presetApplied: 'Применено',
|
||||
deletePreset: 'Удалить',
|
||||
presetDeleted: 'Удалено',
|
||||
confirmOverwriteTitle: 'Уже существует',
|
||||
confirmOverwriteMessage: 'Предустановка с именем "{name}" уже существует. Перезаписать?',
|
||||
cannotDeleteDefault: 'Нельзя удалить стандартную предустановку',
|
||||
adminOnly: 'Только для администратора',
|
||||
selectPlanet: 'Выбрать планету',
|
||||
choosePlanet: 'Выберите планету',
|
||||
@@ -1185,6 +1200,15 @@ export default {
|
||||
}
|
||||
},
|
||||
diplomacy: {
|
||||
sort: {
|
||||
label: 'Сортировка',
|
||||
ascending: 'По возрастанию',
|
||||
descending: 'По убыванию',
|
||||
reputation: 'Репутация',
|
||||
planets: 'Планеты',
|
||||
difficulty: 'Сложность',
|
||||
allies: 'Союзники'
|
||||
},
|
||||
title: 'Дипломатия',
|
||||
description: 'Управление дипломатическими отношениями с NPC',
|
||||
tabs: {
|
||||
|
||||
@@ -948,6 +948,7 @@ export default {
|
||||
exporting: '导出中...',
|
||||
exportSuccess: '导出成功',
|
||||
exportSuccessWithPath: '导出成功,文件已保存到:{path}',
|
||||
exportCopiedToClipboard: '导出成功,数据已复制到剪贴板',
|
||||
storagePermissionDenied: '存储权限被拒绝,无法导出文件',
|
||||
exportFailed: '导出失败,请重试',
|
||||
importData: '导入数据',
|
||||
@@ -1094,6 +1095,20 @@ export default {
|
||||
modifyOfficers: '修改军官',
|
||||
officersDesc: '快速设置军官到期时间',
|
||||
days: '天',
|
||||
presets: '预设',
|
||||
choosePreset: '选择预设',
|
||||
defaultPreset: '默认预设',
|
||||
applyPreset: '应用预设',
|
||||
presetName: '预设名称',
|
||||
savePreset: '保存预设',
|
||||
presetNameRequired: '请输入预设名称',
|
||||
presetSaved: '预设保存成功',
|
||||
presetApplied: '预设应用成功',
|
||||
deletePreset: '删除预设',
|
||||
presetDeleted: '预设已删除',
|
||||
confirmOverwriteTitle: '预设已存在',
|
||||
confirmOverwriteMessage: '名为 "{name}" 的预设已存在,是否覆盖?',
|
||||
cannotDeleteDefault: '无法删除默认预设',
|
||||
npcTesting: 'NPC 测试',
|
||||
npcTestingDesc: '测试NPC侦查和攻击行为',
|
||||
selectNPC: '选择NPC',
|
||||
@@ -1258,6 +1273,15 @@ export default {
|
||||
npcEliminatedMessage: '你消灭了{npcName}的所有星球!该势力已被彻底摧毁。'
|
||||
},
|
||||
searchPlaceholder: '搜索NPC名称...',
|
||||
sort: {
|
||||
label: '排序',
|
||||
ascending: '升序',
|
||||
descending: '降序',
|
||||
reputation: '好感度',
|
||||
planets: '星球数量',
|
||||
difficulty: '难度',
|
||||
allies: '盟友数量'
|
||||
},
|
||||
// 通知类型
|
||||
notificationType: {
|
||||
tradeOffer: '贸易提议',
|
||||
|
||||
@@ -952,6 +952,7 @@ export default {
|
||||
exporting: '匯出中...',
|
||||
exportSuccess: '匯出成功',
|
||||
exportSuccessWithPath: '匯出成功,檔案已儲存到:{path}',
|
||||
exportCopiedToClipboard: '匯出成功,資料已複製到剪貼簿',
|
||||
storagePermissionDenied: '儲存權限被拒絕,無法匯出檔案',
|
||||
exportFailed: '匯出失敗,請重試',
|
||||
importData: '匯入資料',
|
||||
@@ -1079,6 +1080,20 @@ export default {
|
||||
},
|
||||
gmView: {
|
||||
title: 'GM 管理面板',
|
||||
presets: '預設',
|
||||
choosePreset: '選擇預設',
|
||||
defaultPreset: '預設範本',
|
||||
applyPreset: '套用預設',
|
||||
savePreset: '儲存預設',
|
||||
presetName: '預設名稱',
|
||||
presetNameRequired: '請輸入預設名稱',
|
||||
presetSaved: '預設已儲存',
|
||||
presetApplied: '預設已套用',
|
||||
deletePreset: '刪除預設',
|
||||
presetDeleted: '預設已刪除',
|
||||
confirmOverwriteTitle: '預設已存在',
|
||||
confirmOverwriteMessage: '名為 "{name}" 的預設已存在,是否覆蓋?',
|
||||
cannotDeleteDefault: '無法刪除預設範本',
|
||||
adminOnly: '僅管理員',
|
||||
selectPlanet: '選擇星球',
|
||||
choosePlanet: '選擇一個星球',
|
||||
@@ -1178,6 +1193,15 @@ export default {
|
||||
}
|
||||
},
|
||||
diplomacy: {
|
||||
sort: {
|
||||
label: '排序',
|
||||
ascending: '升序',
|
||||
descending: '降序',
|
||||
reputation: '聲望',
|
||||
planets: '星球',
|
||||
difficulty: '難度',
|
||||
allies: '盟友'
|
||||
},
|
||||
title: '外交',
|
||||
description: '管理與NPC的外交關係',
|
||||
tabs: {
|
||||
|
||||
@@ -15,25 +15,37 @@ import { ACHIEVEMENTS, ACHIEVEMENT_MAP, getNextTier, getTierIndex } from '@/conf
|
||||
|
||||
// 初始化空的成就统计数据
|
||||
export const initializeAchievementStats = (): AchievementStats => {
|
||||
const emptyShipRecord = Object.values(ShipType).reduce((acc, type) => {
|
||||
const emptyShipRecord = Object.values(ShipType).reduce(
|
||||
(acc, type) => {
|
||||
acc[type] = 0
|
||||
return acc
|
||||
}, {} as Record<ShipType, number>)
|
||||
},
|
||||
{} as Record<ShipType, number>
|
||||
)
|
||||
|
||||
const emptyDefenseRecord = Object.values(DefenseType).reduce((acc, type) => {
|
||||
const emptyDefenseRecord = Object.values(DefenseType).reduce(
|
||||
(acc, type) => {
|
||||
acc[type] = 0
|
||||
return acc
|
||||
}, {} as Record<DefenseType, number>)
|
||||
},
|
||||
{} as Record<DefenseType, number>
|
||||
)
|
||||
|
||||
const emptyBuildingRecord = Object.values(BuildingType).reduce((acc, type) => {
|
||||
const emptyBuildingRecord = Object.values(BuildingType).reduce(
|
||||
(acc, type) => {
|
||||
acc[type] = 0
|
||||
return acc
|
||||
}, {} as Record<BuildingType, number>)
|
||||
},
|
||||
{} as Record<BuildingType, number>
|
||||
)
|
||||
|
||||
const emptyTechRecord = Object.values(TechnologyType).reduce((acc, type) => {
|
||||
const emptyTechRecord = Object.values(TechnologyType).reduce(
|
||||
(acc, type) => {
|
||||
acc[type] = 0
|
||||
return acc
|
||||
}, {} as Record<TechnologyType, number>)
|
||||
},
|
||||
{} as Record<TechnologyType, number>
|
||||
)
|
||||
|
||||
return {
|
||||
// 资源统计
|
||||
@@ -221,7 +233,8 @@ export const applyAchievementReward = (player: Player, reward: AchievementReward
|
||||
}
|
||||
|
||||
if (reward.points) {
|
||||
player.points += reward.points
|
||||
// 奖励积分存入 bonusPoints,不会被 calculatePlayerPoints 覆盖
|
||||
player.bonusPoints = (player.bonusPoints || 0) + reward.points
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Fleet, Resources, BattleResult, Officer, TechnologyType } from '@/
|
||||
import { DefenseType, OfficerType } from '@/types/game'
|
||||
import { workerManager } from '@/workers/workerManager'
|
||||
import { MOON_CONFIG } from '@/config/gameConfig'
|
||||
import { generateId } from '@/utils/id'
|
||||
|
||||
/**
|
||||
* 执行战斗模拟
|
||||
@@ -66,7 +67,7 @@ export const simulateBattle = async (
|
||||
|
||||
// 生成战斗报告
|
||||
const battleResult: BattleResult = {
|
||||
id: `battle_${Date.now()}`,
|
||||
id: generateId('battle'),
|
||||
timestamp: Date.now(),
|
||||
attackerId: '',
|
||||
defenderId: '',
|
||||
|
||||
@@ -23,44 +23,30 @@ export const calculateBuildingCost = (buildingType: BuildingType, targetLevel: n
|
||||
|
||||
/**
|
||||
* 计算建筑升级时间
|
||||
* 使用 2moons 公式(调整版):
|
||||
* 1. 成本系数 = Σ (资源^0.3 / 0.003)
|
||||
* 2. 时间(秒) = 成本系数 / ((1 + 机器人工厂) × 2^纳米工厂 × 游戏速度)
|
||||
* @param buildingType 建筑类型
|
||||
* @param targetLevel 目标等级
|
||||
* @param buildingSpeedBonus 指挥官等提供的速度加成百分比
|
||||
* @param roboticsFactoryLevel 机器人工厂等级
|
||||
* @param naniteFactoryLevel 纳米工厂等级
|
||||
* @param gameSpeed 游戏速度(默认1)
|
||||
*/
|
||||
export const calculateBuildingTime = (
|
||||
buildingType: BuildingType,
|
||||
targetLevel: number,
|
||||
buildingSpeedBonus: number = 0,
|
||||
roboticsFactoryLevel: number = 0,
|
||||
naniteFactoryLevel: number = 0,
|
||||
gameSpeed: number = 1
|
||||
naniteFactoryLevel: number = 0
|
||||
): number => {
|
||||
// 计算该等级的成本
|
||||
const cost = calculateBuildingCost(buildingType, targetLevel)
|
||||
const config = BUILDINGS[buildingType]
|
||||
const multiplier = Math.pow(config.costMultiplier, targetLevel - 1)
|
||||
const baseTime = config.baseTime * multiplier
|
||||
|
||||
// 2moons 公式:成本系数 = Σ (资源^0.3 / 0.003)
|
||||
let elementCost = 0
|
||||
if (cost.metal > 0) elementCost += Math.pow(cost.metal, 0.3) / 0.003
|
||||
if (cost.crystal > 0) elementCost += Math.pow(cost.crystal, 0.3) / 0.003
|
||||
if (cost.deuterium > 0) elementCost += Math.pow(cost.deuterium, 0.3) / 0.003
|
||||
|
||||
// 机器人工厂和纳米工厂的加速
|
||||
const factoryBonus = (1 + roboticsFactoryLevel) * Math.pow(2, naniteFactoryLevel)
|
||||
|
||||
// 简化公式:时间(秒) = 成本系数 / (工厂加成 × 游戏速度)
|
||||
const timeInSeconds = elementCost / (factoryBonus * gameSpeed)
|
||||
// 机器人工厂和纳米工厂的加速:建造时间 / (1 + 机器人工厂等级 + 纳米工厂等级 × 2)
|
||||
const factorySpeedDivisor = 1 + roboticsFactoryLevel + naniteFactoryLevel * 2
|
||||
|
||||
// 指挥官等的百分比加成
|
||||
const speedMultiplier = 1 - buildingSpeedBonus / 100
|
||||
|
||||
// 确保最小时间为5秒
|
||||
return Math.max(5, Math.floor(timeInSeconds * speedMultiplier))
|
||||
return Math.floor((baseTime / factorySpeedDivisor) * speedMultiplier)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,19 +64,23 @@ export const calculateUsedSpace = (planet: Planet): number => {
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查建筑升级条件
|
||||
* 检查建筑升级条件(包括基础要求和等级门槛要求)
|
||||
*/
|
||||
export const checkBuildingRequirements = (
|
||||
buildingType: BuildingType,
|
||||
planet: Planet,
|
||||
technologies: Partial<Record<TechnologyType, number>>
|
||||
technologies: Partial<Record<TechnologyType, number>>,
|
||||
targetLevel?: number
|
||||
): boolean => {
|
||||
const config = BUILDINGS[buildingType]
|
||||
const requirements = (config as any).requirements
|
||||
if (!requirements) return true
|
||||
const currentLevel = planet.buildings[buildingType] || 0
|
||||
const level = targetLevel ?? currentLevel + 1
|
||||
|
||||
for (const [key, level] of Object.entries(requirements)) {
|
||||
const requiredLevel = level as number
|
||||
// 检查基础 requirements
|
||||
const requirements = (config as any).requirements
|
||||
if (requirements) {
|
||||
for (const [key, reqLevel] of Object.entries(requirements)) {
|
||||
const requiredLevel = reqLevel as number
|
||||
if (Object.values(BuildingType).includes(key as BuildingType)) {
|
||||
const requiredBuildingType = key as BuildingType
|
||||
const requiredBuildingConfig = BUILDINGS[requiredBuildingType]
|
||||
@@ -110,6 +100,44 @@ export const checkBuildingRequirements = (
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 检查等级门槛 levelRequirements
|
||||
const levelRequirements = (config as any).levelRequirements
|
||||
if (levelRequirements) {
|
||||
// 找出所有小于等于目标等级的门槛
|
||||
const applicableLevels = Object.keys(levelRequirements)
|
||||
.map(Number)
|
||||
.filter(l => l <= level)
|
||||
.sort((a, b) => a - b)
|
||||
|
||||
for (const threshold of applicableLevels) {
|
||||
const reqs = levelRequirements[threshold]
|
||||
if (!reqs) continue
|
||||
|
||||
for (const [key, reqLevel] of Object.entries(reqs)) {
|
||||
const requiredLevel = reqLevel as number
|
||||
if (Object.values(BuildingType).includes(key as BuildingType)) {
|
||||
const requiredBuildingType = key as BuildingType
|
||||
const requiredBuildingConfig = BUILDINGS[requiredBuildingType]
|
||||
|
||||
// 如果当前是月球,且所需建筑是星球专属建筑(planetOnly),则跳过此前置条件
|
||||
if (planet.isMoon && requiredBuildingConfig?.planetOnly) {
|
||||
continue
|
||||
}
|
||||
|
||||
if ((planet.buildings[requiredBuildingType] || 0) < requiredLevel) {
|
||||
return false
|
||||
}
|
||||
} else if (Object.values(TechnologyType).includes(key as TechnologyType)) {
|
||||
if ((technologies[key as TechnologyType] || 0) < requiredLevel) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
type ShipType
|
||||
} from '@/types/game'
|
||||
import { MAIN_CAMPAIGN, getAllQuests, getQuestById, getQuestsByChapter } from '@/config/campaignConfig'
|
||||
import { generateId } from '@/utils/id'
|
||||
import * as resourceLogic from './resourceLogic'
|
||||
|
||||
/**
|
||||
@@ -364,7 +365,8 @@ export const claimQuestRewards = (
|
||||
}
|
||||
|
||||
if (rewards.points) {
|
||||
player.points += rewards.points
|
||||
// 奖励积分存入 bonusPoints,不会被 calculatePlayerPoints 覆盖
|
||||
player.bonusPoints = (player.bonusPoints || 0) + rewards.points
|
||||
}
|
||||
|
||||
if (rewards.ships && currentPlanet) {
|
||||
@@ -514,7 +516,7 @@ export const createQuestNotification = (
|
||||
): QuestNotification => {
|
||||
const quest = getQuestById(questId)
|
||||
return {
|
||||
id: `quest_notification_${Date.now()}`,
|
||||
id: generateId('quest_notification'),
|
||||
timestamp: Date.now(),
|
||||
questId,
|
||||
questTitleKey: quest?.titleKey || '',
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Locale } from '@/locales'
|
||||
import { ShipType, DefenseType, MissionType, BuildingType, OfficerType, TechnologyType, ExpeditionZone } from '@/types/game'
|
||||
import { FLEET_STORAGE_CONFIG, EXPEDITION_ZONES } from '@/config/gameConfig'
|
||||
import { useGameStore } from '@/stores/gameStore'
|
||||
import { generateId } from '@/utils/id'
|
||||
import * as battleLogic from './battleLogic'
|
||||
import * as moonLogic from './moonLogic'
|
||||
import * as moonValidation from './moonValidation'
|
||||
@@ -61,7 +62,7 @@ export const createFleetMission = (
|
||||
): FleetMission => {
|
||||
const now = Date.now()
|
||||
return {
|
||||
id: `mission_${now}`,
|
||||
id: generateId('mission'),
|
||||
playerId,
|
||||
originPlanetId,
|
||||
// 深拷贝targetPosition,避免多个任务共享同一个引用
|
||||
@@ -171,7 +172,7 @@ export const processAttackArrival = async (
|
||||
)
|
||||
|
||||
// 更新战斗报告ID
|
||||
battleResult.id = `battle_${Date.now()}`
|
||||
battleResult.id = generateId('battle')
|
||||
battleResult.attackerId = attacker.id
|
||||
battleResult.defenderId = targetPlanet.ownerId || 'unknown'
|
||||
battleResult.attackerPlanetId = mission.originPlanetId
|
||||
@@ -267,7 +268,7 @@ export const processNPCAttackArrival = async (
|
||||
)
|
||||
|
||||
// 更新战斗报告ID和参与者信息
|
||||
battleResult.id = `battle_${Date.now()}`
|
||||
battleResult.id = generateId('battle')
|
||||
battleResult.attackerId = npc.id
|
||||
battleResult.defenderId = defender.id
|
||||
battleResult.attackerPlanetId = mission.originPlanetId
|
||||
@@ -414,7 +415,7 @@ export const processColonizeArrival = (
|
||||
|
||||
// 创建新殖民地
|
||||
const newPlanet: Planet = {
|
||||
id: `planet_${Date.now()}`,
|
||||
id: generateId('planet'),
|
||||
name: `${colonyNameTemplate} ${mission.targetPosition.galaxy}:${mission.targetPosition.system}:${mission.targetPosition.position}`,
|
||||
ownerId: player.id,
|
||||
position: mission.targetPosition,
|
||||
@@ -564,7 +565,7 @@ export const processSpyArrival = (
|
||||
const wasDetected = Math.random() < detectionChance
|
||||
|
||||
const spyReport: SpyReport = {
|
||||
id: `spy_${Date.now()}`,
|
||||
id: generateId('spy'),
|
||||
timestamp: Date.now(),
|
||||
spyId: attacker.id,
|
||||
targetPlanetId: targetPlanet.id,
|
||||
@@ -1050,7 +1051,7 @@ export const processDestroyArrival = async (
|
||||
)
|
||||
|
||||
// 更新战斗报告
|
||||
battleResult.id = `battle_${Date.now()}`
|
||||
battleResult.id = generateId('battle')
|
||||
battleResult.attackerId = attacker.id
|
||||
battleResult.defenderId = targetPlanet.ownerId || 'unknown'
|
||||
battleResult.attackerPlanetId = mission.originPlanetId
|
||||
|
||||
@@ -149,7 +149,33 @@ export const processGameUpdate = (
|
||||
}
|
||||
}
|
||||
|
||||
// 更新所有星球资源(直接同步计算,避免 Worker 通信开销)
|
||||
// 收集所有新解锁的内容
|
||||
const allUnlockedItems: UnlockedItem[] = []
|
||||
|
||||
// 先完成所有星球的建造队列(升级建筑),确保资源更新时使用新的建筑等级
|
||||
player.planets.forEach(planet => {
|
||||
// 保存完成前的建筑状态
|
||||
const previousBuildings = { ...planet.buildings }
|
||||
|
||||
// 检查建造队列
|
||||
buildingLogic.completeBuildQueue(planet, now, onPointsEarned, onCompleted)
|
||||
|
||||
// 检查新解锁(只在主星球上检查,避免重复通知)
|
||||
if (!planet.isMoon && onUnlock) {
|
||||
const unlockedItems = unlockLogic.checkAllNewlyUnlocked(planet, player.technologies, previousBuildings, previousTechnologies)
|
||||
allUnlockedItems.push(...unlockedItems)
|
||||
}
|
||||
|
||||
// 更新星球最大空间
|
||||
if (planet.isMoon) {
|
||||
planet.maxSpace = planetLogic.calculateMoonMaxSpace(planet)
|
||||
} else {
|
||||
const terraformingTechLevel = player.technologies[TechnologyType.TerraformingTechnology] || 0
|
||||
planet.maxSpace = planetLogic.calculatePlanetMaxSpace(planet, terraformingTechLevel)
|
||||
}
|
||||
})
|
||||
|
||||
// 然后更新所有星球资源(使用新的建筑等级计算生产)
|
||||
// 获取采矿技术等级(用于矿脉恢复上限计算)
|
||||
const miningTechLevel = player.technologies[TechnologyType.MiningTechnology] || 0
|
||||
// 获取资源研究科技等级
|
||||
@@ -183,32 +209,6 @@ export const processGameUpdate = (
|
||||
}
|
||||
})
|
||||
|
||||
// 收集所有新解锁的内容
|
||||
const allUnlockedItems: UnlockedItem[] = []
|
||||
|
||||
// 更新所有星球其他状态
|
||||
player.planets.forEach(planet => {
|
||||
// 保存完成前的建筑状态
|
||||
const previousBuildings = { ...planet.buildings }
|
||||
|
||||
// 检查建造队列
|
||||
buildingLogic.completeBuildQueue(planet, now, onPointsEarned, onCompleted)
|
||||
|
||||
// 检查新解锁(只在主星球上检查,避免重复通知)
|
||||
if (!planet.isMoon && onUnlock) {
|
||||
const unlockedItems = unlockLogic.checkAllNewlyUnlocked(planet, player.technologies, previousBuildings, previousTechnologies)
|
||||
allUnlockedItems.push(...unlockedItems)
|
||||
}
|
||||
|
||||
// 更新星球最大空间
|
||||
if (planet.isMoon) {
|
||||
planet.maxSpace = planetLogic.calculateMoonMaxSpace(planet)
|
||||
} else {
|
||||
const terraformingTechLevel = player.technologies[TechnologyType.TerraformingTechnology] || 0
|
||||
planet.maxSpace = planetLogic.calculatePlanetMaxSpace(planet, terraformingTechLevel)
|
||||
}
|
||||
})
|
||||
|
||||
// 检查研究队列
|
||||
const updatedResearchQueue = researchLogic.completeResearchQueue(
|
||||
player.researchQueue,
|
||||
|
||||
@@ -3,8 +3,66 @@
|
||||
* 处理星际导弹攻击、射程计算、拦截等
|
||||
*/
|
||||
|
||||
import type { Planet, MissileAttack, DefenseType, TechnologyType, Position } from '@/types/game'
|
||||
import { DefenseType as DefenseTypes } from '@/types/game'
|
||||
import type { Planet, MissileAttack, DefenseType, TechnologyType, Position, BuildQueueItem } from '@/types/game'
|
||||
import { DefenseType as DefenseTypes, BuildingType } from '@/types/game'
|
||||
|
||||
/**
|
||||
* 计算导弹发射井容量
|
||||
*/
|
||||
export const calculateMissileSiloCapacity = (buildings: Partial<Record<BuildingType, number>>): number => {
|
||||
const siloLevel = buildings[BuildingType.MissileSilo] || 0
|
||||
return siloLevel * 10 // 每级存储10枚导弹
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算当前导弹总数
|
||||
*/
|
||||
export const calculateCurrentMissileCount = (defense: Partial<Record<DefenseType, number>>): number => {
|
||||
const interplanetaryMissiles = defense[DefenseTypes.InterplanetaryMissile] || 0
|
||||
const antiBallisticMissiles = defense[DefenseTypes.AntiBallisticMissile] || 0
|
||||
return interplanetaryMissiles + antiBallisticMissiles
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算建造队列中的导弹总数
|
||||
*/
|
||||
export const calculateQueueMissileCount = (buildQueue: BuildQueueItem[]): number => {
|
||||
let queueMissileCount = 0
|
||||
|
||||
for (const item of buildQueue) {
|
||||
if (item.type === 'defense') {
|
||||
const defenseType = item.itemType as DefenseType
|
||||
if (defenseType === DefenseTypes.InterplanetaryMissile || defenseType === DefenseTypes.AntiBallisticMissile) {
|
||||
queueMissileCount += item.quantity || 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return queueMissileCount
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查导弹容量限制
|
||||
*/
|
||||
export const checkMissileSiloLimit = (
|
||||
defenseType: DefenseType,
|
||||
currentDefense: Partial<Record<DefenseType, number>>,
|
||||
buildings: Partial<Record<BuildingType, number>>,
|
||||
quantity: number,
|
||||
buildQueue?: BuildQueueItem[]
|
||||
): boolean => {
|
||||
// 只对导弹类型进行检查
|
||||
if (defenseType !== DefenseTypes.InterplanetaryMissile && defenseType !== DefenseTypes.AntiBallisticMissile) {
|
||||
return true
|
||||
}
|
||||
|
||||
const maxCapacity = calculateMissileSiloCapacity(buildings)
|
||||
const currentCount = calculateCurrentMissileCount(currentDefense)
|
||||
const queueCount = buildQueue ? calculateQueueMissileCount(buildQueue) : 0
|
||||
const newCount = currentCount + queueCount + quantity
|
||||
|
||||
return newCount <= maxCapacity
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算导弹射程(基于脉冲引擎等级)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Planet, Resources } from '@/types/game'
|
||||
import { BuildingType, ShipType, DefenseType } from '@/types/game'
|
||||
import { MOON_CONFIG, FLEET_STORAGE_CONFIG } from '@/config/gameConfig'
|
||||
import { generateId } from '@/utils/id'
|
||||
|
||||
/**
|
||||
* 计算月球生成概率
|
||||
@@ -79,7 +80,7 @@ export const tryGenerateMoon = (
|
||||
|
||||
// 生成月球
|
||||
const moon: Planet = {
|
||||
id: `moon_${Date.now()}`,
|
||||
id: generateId('moon'),
|
||||
name: `Moon [${planetPosition.galaxy}:${planetPosition.system}:${planetPosition.position}]`,
|
||||
ownerId: playerId,
|
||||
position: planetPosition,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Planet, Resources } from '@/types/game'
|
||||
import { ShipType, DefenseType, BuildingType } from '@/types/game'
|
||||
import { MOON_CONFIG, PLANET_CONFIG, FLEET_STORAGE_CONFIG } from '@/config/gameConfig'
|
||||
import { generateId } from '@/utils/id'
|
||||
import * as oreDepositLogic from './oreDepositLogic'
|
||||
|
||||
/**
|
||||
@@ -173,7 +174,7 @@ export const createMoon = (
|
||||
moonSuffix: string = "'s Moon",
|
||||
diameter?: number
|
||||
): Planet => {
|
||||
const moonId = `moon_${Date.now()}`
|
||||
const moonId = generateId('moon')
|
||||
const moon: Planet = {
|
||||
id: moonId,
|
||||
name: `${parentPlanet.name}${moonSuffix}`,
|
||||
@@ -237,7 +238,7 @@ export const createMoon = (
|
||||
|
||||
/**
|
||||
* 计算月球空间上限
|
||||
* OGame规则:月球初始1格,月球基地每级+3格(但月球基地本身占用1格,净增2格)
|
||||
* OGame规则:月球初始1格,月球基地每级+30格
|
||||
*/
|
||||
export const calculateMoonMaxSpace = (moon: Planet): number => {
|
||||
if (!moon.isMoon) return 0
|
||||
|
||||
@@ -72,7 +72,16 @@ export const checkRequirements = (
|
||||
for (const [key, requiredLevel] of Object.entries(requirements)) {
|
||||
// 检查是否为建筑类型
|
||||
if (Object.values(BuildingType).includes(key as BuildingType)) {
|
||||
const currentLevel = planet.buildings[key as BuildingType] || 0
|
||||
const requiredBuildingType = key as BuildingType
|
||||
const requiredBuildingConfig = BUILDINGS[requiredBuildingType]
|
||||
|
||||
// 如果当前是月球,且所需建筑是星球专属建筑(planetOnly),则跳过此前置条件
|
||||
// 这允许在月球上建造机器人工厂等建筑,即使它们的前置条件是无法在月球建造的矿场
|
||||
if (planet.isMoon && requiredBuildingConfig?.planetOnly) {
|
||||
continue
|
||||
}
|
||||
|
||||
const currentLevel = planet.buildings[requiredBuildingType] || 0
|
||||
if (currentLevel < requiredLevel) {
|
||||
return false
|
||||
}
|
||||
@@ -164,7 +173,7 @@ export const getMaxFleetMissions = (additionalFleetSlots: number = 0, computerTe
|
||||
* @param level 目标等级
|
||||
* @returns 总资源成本(金属+水晶+重氢)
|
||||
*/
|
||||
const calculateBuildingTotalCost = (buildingType: BuildingType, level: number): number => {
|
||||
export const calculateBuildingTotalCost = (buildingType: BuildingType, level: number): number => {
|
||||
if (level <= 0) return 0
|
||||
|
||||
const config = BUILDINGS[buildingType]
|
||||
@@ -192,7 +201,7 @@ const calculateBuildingTotalCost = (buildingType: BuildingType, level: number):
|
||||
* @param level 目标等级
|
||||
* @returns 总资源成本(金属+水晶+重氢)
|
||||
*/
|
||||
const calculateTechnologyTotalCost = (techType: TechnologyType, level: number): number => {
|
||||
export const calculateTechnologyTotalCost = (techType: TechnologyType, level: number): number => {
|
||||
if (level <= 0) return 0
|
||||
|
||||
const config = TECHNOLOGIES[techType]
|
||||
@@ -219,7 +228,7 @@ const calculateTechnologyTotalCost = (techType: TechnologyType, level: number):
|
||||
* @param shipType 舰船类型
|
||||
* @returns 单个舰船的资源成本(金属+水晶+重氢)
|
||||
*/
|
||||
const calculateShipUnitCost = (shipType: ShipType): number => {
|
||||
export const calculateShipUnitCost = (shipType: ShipType): number => {
|
||||
const config = SHIPS[shipType]
|
||||
if (!config) return 0
|
||||
|
||||
@@ -231,7 +240,7 @@ const calculateShipUnitCost = (shipType: ShipType): number => {
|
||||
* @param defenseType 防御类型
|
||||
* @returns 单个防御的资源成本(金属+水晶+重氢)
|
||||
*/
|
||||
const calculateDefenseUnitCost = (defenseType: DefenseType): number => {
|
||||
export const calculateDefenseUnitCost = (defenseType: DefenseType): number => {
|
||||
const config = DEFENSES[defenseType]
|
||||
if (!config) return 0
|
||||
|
||||
@@ -273,6 +282,11 @@ export const calculatePlayerPoints = (player: Player): number => {
|
||||
})
|
||||
})
|
||||
|
||||
// 每1000资源 = 1积分
|
||||
return Math.floor(totalCost / 1000)
|
||||
// 每1000资源 = 1积分(基础积分)
|
||||
const basePoints = Math.floor(totalCost / 1000)
|
||||
|
||||
// 加上奖励积分(战役、成就等奖励的积分)
|
||||
const bonusPoints = player.bonusPoints || 0
|
||||
|
||||
return basePoints + bonusPoints
|
||||
}
|
||||
|
||||
@@ -156,64 +156,6 @@ export const checkShieldDomeLimit = (
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算导弹发射井容量
|
||||
*/
|
||||
export const calculateMissileSiloCapacity = (buildings: Partial<Record<BuildingType, number>>): number => {
|
||||
const siloLevel = buildings[BuildingType.MissileSilo] || 0
|
||||
return siloLevel * 10 // 每级存储10枚导弹
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算当前导弹总数
|
||||
*/
|
||||
export const calculateCurrentMissileCount = (defense: Partial<Record<DefenseType, number>>): number => {
|
||||
const interplanetaryMissiles = defense[DefenseType.InterplanetaryMissile] || 0
|
||||
const antiBallisticMissiles = defense[DefenseType.AntiBallisticMissile] || 0
|
||||
return interplanetaryMissiles + antiBallisticMissiles
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算建造队列中的导弹总数
|
||||
*/
|
||||
export const calculateQueueMissileCount = (buildQueue: Array<{ type: string; itemType: string; quantity?: number }>): number => {
|
||||
let queueMissileCount = 0
|
||||
|
||||
for (const item of buildQueue) {
|
||||
if (item.type === 'defense') {
|
||||
const defenseType = item.itemType as DefenseType
|
||||
if (defenseType === DefenseType.InterplanetaryMissile || defenseType === DefenseType.AntiBallisticMissile) {
|
||||
queueMissileCount += item.quantity || 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return queueMissileCount
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查导弹容量限制
|
||||
*/
|
||||
export const checkMissileSiloLimit = (
|
||||
defenseType: DefenseType,
|
||||
currentDefense: Partial<Record<DefenseType, number>>,
|
||||
buildings: Partial<Record<BuildingType, number>>,
|
||||
quantity: number,
|
||||
buildQueue?: Array<{ type: string; itemType: string; quantity?: number }>
|
||||
): boolean => {
|
||||
// 只对导弹类型进行检查
|
||||
if (defenseType !== DefenseType.InterplanetaryMissile && defenseType !== DefenseType.AntiBallisticMissile) {
|
||||
return true
|
||||
}
|
||||
|
||||
const maxCapacity = calculateMissileSiloCapacity(buildings)
|
||||
const currentCount = calculateCurrentMissileCount(currentDefense)
|
||||
const queueCount = buildQueue ? calculateQueueMissileCount(buildQueue) : 0
|
||||
const newCount = currentCount + queueCount + quantity
|
||||
|
||||
return newCount <= maxCapacity
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建舰船建造队列项
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Planet, Resources, BuildQueueItem, Fleet, Officer } from '@/types/game'
|
||||
import { ShipType, DefenseType, TechnologyType, OfficerType, BuildingType } from '@/types/game'
|
||||
import * as shipLogic from './shipLogic'
|
||||
import * as missileLogic from './missileLogic'
|
||||
import * as resourceLogic from './resourceLogic'
|
||||
import * as officerLogic from './officerLogic'
|
||||
import * as publicLogic from './publicLogic'
|
||||
@@ -101,7 +102,7 @@ export const validateDefenseBuild = (
|
||||
}
|
||||
|
||||
// 导弹发射井容量限制
|
||||
if (!shipLogic.checkMissileSiloLimit(defenseType, planet.defense, planet.buildings, quantity, planet.buildQueue)) {
|
||||
if (!missileLogic.checkMissileSiloLimit(defenseType, planet.defense, planet.buildings, quantity, planet.buildQueue)) {
|
||||
return { valid: false, reason: 'errors.missileSiloLimit' }
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ export const useGameStore = defineStore('game', {
|
||||
giftNotifications: [],
|
||||
giftRejectedNotifications: [],
|
||||
points: 0,
|
||||
bonusPoints: 0,
|
||||
isGMEnabled: false, // 明确设置 GM 模式默认为 false
|
||||
lastVersionCheckTime: 0, // 最后一次检查版本的时间戳,默认为0
|
||||
achievementStats: initializeAchievementStats() as AchievementStats,
|
||||
|
||||
@@ -799,6 +799,7 @@ export interface Player {
|
||||
allyDefenseNotifications?: AllyDefenseNotification[] // 友好NPC协防通知
|
||||
attitudeChangeNotifications?: AttitudeChangeNotification[] // NPC态度变化通知
|
||||
points: number // 总积分(每1000资源=1分)
|
||||
bonusPoints?: number // 奖励积分(战役、成就等奖励的积分,不会被重新计算覆盖)
|
||||
isGMEnabled?: boolean // GM模式开关(默认false,通过秘籍激活)
|
||||
lastVersionCheckTime?: number // 最后一次自动检查版本的时间戳(被动检测)
|
||||
lastManualUpdateCheck?: number // 最后一次手动检查更新的时间戳(主动检测)
|
||||
|
||||
8
src/utils/id.ts
Normal file
8
src/utils/id.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* 统一生成带前缀的业务ID
|
||||
* 便于后续集中调整ID规则
|
||||
*/
|
||||
export const generateId = (prefix: string): string => {
|
||||
const timestamp = Date.now()
|
||||
return `${prefix}_${timestamp}_${Math.random().toString(36).slice(2, 9)}`
|
||||
}
|
||||
@@ -1,4 +1,18 @@
|
||||
import type { Planet, DebrisField, NPC } from '@/types/game'
|
||||
import type {
|
||||
AllyDefenseNotification,
|
||||
DebrisField,
|
||||
FleetMission,
|
||||
IncomingFleetAlert,
|
||||
JointAttackInvite,
|
||||
MissionReport,
|
||||
NPC,
|
||||
NPCActivityNotification,
|
||||
Planet,
|
||||
Player,
|
||||
Position,
|
||||
SpiedNotification,
|
||||
SpyReport
|
||||
} from '@/types/game'
|
||||
import { decryptData, encryptData } from './crypto'
|
||||
import { generatePlanetTemperature } from '@/logic/planetLogic'
|
||||
import pkg from '../../package.json'
|
||||
@@ -8,6 +22,514 @@ import pkg from '../../package.json'
|
||||
* 用于从旧版本数据结构迁移到新版本
|
||||
*/
|
||||
|
||||
type PlanetKind = 'planet' | 'moon'
|
||||
type RemappedPlanetEntry = { newId: string; name: string }
|
||||
type DuplicatePlanetKindMap = Map<PlanetKind, RemappedPlanetEntry>
|
||||
type DuplicatePlanetPositionMap = Map<string, DuplicatePlanetKindMap>
|
||||
|
||||
// oldPlanetId -> position -> planet/moon -> remapped target
|
||||
type DuplicatePlanetIdMap = Map<string, DuplicatePlanetPositionMap>
|
||||
|
||||
interface MigratablePlayer extends Player {
|
||||
diplomaticRelations?: Record<string, unknown>
|
||||
}
|
||||
|
||||
interface MigratableGameData {
|
||||
currentPlanetId?: string
|
||||
player?: MigratablePlayer
|
||||
npcs?: NPC[]
|
||||
universePlanets?: Record<string, Planet>
|
||||
debrisFields?: Record<string, DebrisField>
|
||||
}
|
||||
|
||||
interface PlanetReferenceContext {
|
||||
position?: Position
|
||||
isMoon?: boolean
|
||||
planetName?: string
|
||||
}
|
||||
|
||||
interface HasTargetPlanetId {
|
||||
targetPlanetId?: string
|
||||
}
|
||||
|
||||
interface HasOriginPlanetId {
|
||||
originPlanetId?: string
|
||||
}
|
||||
|
||||
interface HasParentPlanetId {
|
||||
parentPlanetId?: string
|
||||
}
|
||||
|
||||
interface HasCurrentPlanetId {
|
||||
currentPlanetId?: string
|
||||
}
|
||||
|
||||
const getPlanetPositionKey = (position: Position): string => {
|
||||
return `${position.galaxy}:${position.system}:${position.position}`
|
||||
}
|
||||
|
||||
const getPlanetKindKey = (isMoon?: boolean): PlanetKind => {
|
||||
return isMoon ? 'moon' : 'planet'
|
||||
}
|
||||
|
||||
const getPlanetEntriesFor = (
|
||||
planetId: string,
|
||||
idMap: DuplicatePlanetIdMap,
|
||||
position?: Position
|
||||
): DuplicatePlanetKindMap | undefined => {
|
||||
if (!position) return undefined
|
||||
|
||||
return idMap.get(planetId)?.get(getPlanetPositionKey(position))
|
||||
}
|
||||
|
||||
const getEntriesByName = (entries: Iterable<RemappedPlanetEntry>, planetName?: string): RemappedPlanetEntry[] => {
|
||||
if (!planetName) {
|
||||
return []
|
||||
}
|
||||
|
||||
return Array.from(entries).filter(entry => entry.name === planetName)
|
||||
}
|
||||
|
||||
const getUniqueEntryByName = (entries: Iterable<RemappedPlanetEntry>, planetName?: string): RemappedPlanetEntry | undefined => {
|
||||
const matchedEntries = getEntriesByName(entries, planetName)
|
||||
if (matchedEntries.length !== 1) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return matchedEntries[0]
|
||||
}
|
||||
|
||||
const getOnlyEntry = (entries: DuplicatePlanetKindMap): RemappedPlanetEntry | undefined => {
|
||||
if (entries.size !== 1) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return Array.from(entries.values())[0]
|
||||
}
|
||||
|
||||
const getEntriesAcrossPositions = (byPosition: DuplicatePlanetPositionMap): RemappedPlanetEntry[] => {
|
||||
const entries: RemappedPlanetEntry[] = []
|
||||
|
||||
byPosition.forEach(byKind => {
|
||||
byKind.forEach(entry => {
|
||||
entries.push(entry)
|
||||
})
|
||||
})
|
||||
|
||||
return entries
|
||||
}
|
||||
|
||||
const buildDuplicatePlanetIdMap = (player: Player): DuplicatePlanetIdMap => {
|
||||
const planetsByOriginalId = new Map<string, Planet[]>()
|
||||
|
||||
player.planets.forEach(planet => {
|
||||
let group = planetsByOriginalId.get(planet.id)
|
||||
if (!group) {
|
||||
group = []
|
||||
planetsByOriginalId.set(planet.id, group)
|
||||
}
|
||||
group.push(planet)
|
||||
})
|
||||
|
||||
const idMap: DuplicatePlanetIdMap = new Map()
|
||||
|
||||
planetsByOriginalId.forEach((planets, originalId) => {
|
||||
if (planets.length <= 1) return
|
||||
|
||||
planets.forEach((planet, index) => {
|
||||
if (index === 0) return
|
||||
|
||||
const newId = `${originalId}_${Math.random().toString(36).substring(2, 9)}`
|
||||
const positionKey = getPlanetPositionKey(planet.position)
|
||||
|
||||
let byPosition = idMap.get(originalId)
|
||||
if (!byPosition) {
|
||||
byPosition = new Map()
|
||||
idMap.set(originalId, byPosition)
|
||||
}
|
||||
|
||||
let byKind = byPosition.get(positionKey)
|
||||
if (!byKind) {
|
||||
byKind = new Map()
|
||||
byPosition.set(positionKey, byKind)
|
||||
}
|
||||
|
||||
byKind.set(getPlanetKindKey(planet.isMoon), {
|
||||
newId,
|
||||
name: planet.name
|
||||
})
|
||||
|
||||
planet.id = newId
|
||||
})
|
||||
})
|
||||
|
||||
return idMap
|
||||
}
|
||||
|
||||
const resolveRemappedPlanetId = (
|
||||
planetId: string | undefined,
|
||||
idMap: DuplicatePlanetIdMap,
|
||||
context: PlanetReferenceContext = {}
|
||||
): string | undefined => {
|
||||
if (!planetId) return undefined
|
||||
|
||||
const byPosition = idMap.get(planetId)
|
||||
if (!byPosition) return undefined
|
||||
|
||||
if (context.position) {
|
||||
const byKind = getPlanetEntriesFor(planetId, idMap, context.position)
|
||||
if (!byKind) return undefined
|
||||
|
||||
// 只有在位置或名称足够区分目标时才重写引用,避免把旧引用误指到错误星球
|
||||
if (context.isMoon !== undefined) {
|
||||
return byKind.get(getPlanetKindKey(context.isMoon))?.newId
|
||||
}
|
||||
|
||||
const matchedByName = getUniqueEntryByName(byKind.values(), context.planetName)
|
||||
if (matchedByName) {
|
||||
return matchedByName.newId
|
||||
}
|
||||
|
||||
return getOnlyEntry(byKind)?.newId
|
||||
}
|
||||
|
||||
if (context.planetName) {
|
||||
return getUniqueEntryByName(getEntriesAcrossPositions(byPosition), context.planetName)?.newId
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
const getUpdatedPlanetId = (
|
||||
currentPlanetId: string | undefined,
|
||||
idMap: DuplicatePlanetIdMap,
|
||||
context: PlanetReferenceContext = {}
|
||||
): string | undefined => {
|
||||
const remappedPlanetId = resolveRemappedPlanetId(currentPlanetId, idMap, context)
|
||||
if (!remappedPlanetId || remappedPlanetId === currentPlanetId) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return remappedPlanetId
|
||||
}
|
||||
|
||||
const updateTargetPlanetId = (
|
||||
target: HasTargetPlanetId,
|
||||
idMap: DuplicatePlanetIdMap,
|
||||
context: PlanetReferenceContext = {}
|
||||
): boolean => {
|
||||
const remappedPlanetId = getUpdatedPlanetId(target.targetPlanetId, idMap, context)
|
||||
if (!remappedPlanetId) {
|
||||
return false
|
||||
}
|
||||
|
||||
target.targetPlanetId = remappedPlanetId
|
||||
return true
|
||||
}
|
||||
|
||||
const updateOriginPlanetId = (
|
||||
target: HasOriginPlanetId,
|
||||
idMap: DuplicatePlanetIdMap,
|
||||
context: PlanetReferenceContext = {}
|
||||
): boolean => {
|
||||
const remappedPlanetId = getUpdatedPlanetId(target.originPlanetId, idMap, context)
|
||||
if (!remappedPlanetId) {
|
||||
return false
|
||||
}
|
||||
|
||||
target.originPlanetId = remappedPlanetId
|
||||
return true
|
||||
}
|
||||
|
||||
const updateParentPlanetId = (
|
||||
target: HasParentPlanetId,
|
||||
idMap: DuplicatePlanetIdMap,
|
||||
context: PlanetReferenceContext = {}
|
||||
): boolean => {
|
||||
const remappedPlanetId = getUpdatedPlanetId(target.parentPlanetId, idMap, context)
|
||||
if (!remappedPlanetId) {
|
||||
return false
|
||||
}
|
||||
|
||||
target.parentPlanetId = remappedPlanetId
|
||||
return true
|
||||
}
|
||||
|
||||
const updateCurrentPlanetId = (
|
||||
target: HasCurrentPlanetId,
|
||||
idMap: DuplicatePlanetIdMap,
|
||||
context: PlanetReferenceContext = {}
|
||||
): boolean => {
|
||||
const remappedPlanetId = getUpdatedPlanetId(target.currentPlanetId, idMap, context)
|
||||
if (!remappedPlanetId) {
|
||||
return false
|
||||
}
|
||||
|
||||
target.currentPlanetId = remappedPlanetId
|
||||
return true
|
||||
}
|
||||
|
||||
const updateMissionTargetPlanetId = (mission: FleetMission, idMap: DuplicatePlanetIdMap): boolean => {
|
||||
return updateTargetPlanetId(mission, idMap, {
|
||||
position: mission.targetPosition,
|
||||
isMoon: mission.targetIsMoon
|
||||
})
|
||||
}
|
||||
|
||||
const updateSpyReportTargetPlanetId = (report: SpyReport, idMap: DuplicatePlanetIdMap): boolean => {
|
||||
return updateTargetPlanetId(report, idMap, {
|
||||
position: report.targetPosition,
|
||||
planetName: report.targetPlanetName
|
||||
})
|
||||
}
|
||||
|
||||
const updateSpiedNotificationTargetPlanetId = (
|
||||
notification: SpiedNotification,
|
||||
idMap: DuplicatePlanetIdMap
|
||||
): boolean => {
|
||||
return updateTargetPlanetId(notification, idMap, {
|
||||
planetName: notification.targetPlanetName
|
||||
})
|
||||
}
|
||||
|
||||
const updateNPCActivityTargetPlanetId = (
|
||||
notification: NPCActivityNotification,
|
||||
idMap: DuplicatePlanetIdMap
|
||||
): boolean => {
|
||||
return updateTargetPlanetId(notification, idMap, {
|
||||
position: notification.targetPosition,
|
||||
planetName: notification.targetPlanetName
|
||||
})
|
||||
}
|
||||
|
||||
const updateIncomingAlertTargetPlanetId = (
|
||||
alert: IncomingFleetAlert,
|
||||
idMap: DuplicatePlanetIdMap
|
||||
): boolean => {
|
||||
return updateTargetPlanetId(alert, idMap, {
|
||||
planetName: alert.targetPlanetName
|
||||
})
|
||||
}
|
||||
|
||||
const updateJointAttackTargetPlanetId = (
|
||||
invite: JointAttackInvite,
|
||||
idMap: DuplicatePlanetIdMap
|
||||
): boolean => {
|
||||
return updateTargetPlanetId(invite, idMap, {
|
||||
position: invite.targetPosition
|
||||
})
|
||||
}
|
||||
|
||||
const updateAllyDefenseTargetPlanetId = (
|
||||
notification: AllyDefenseNotification,
|
||||
idMap: DuplicatePlanetIdMap
|
||||
): boolean => {
|
||||
return updateTargetPlanetId(notification, idMap, {
|
||||
planetName: notification.targetPlanetName
|
||||
})
|
||||
}
|
||||
|
||||
const updateMissionReportPlanetIds = (report: MissionReport, idMap: DuplicatePlanetIdMap): boolean => {
|
||||
let mutated = false
|
||||
|
||||
if (updateOriginPlanetId(report, idMap, {
|
||||
planetName: report.originPlanetName
|
||||
})) {
|
||||
mutated = true
|
||||
}
|
||||
|
||||
if (updateTargetPlanetId(report, idMap, {
|
||||
position: report.targetPosition,
|
||||
planetName: report.targetPlanetName
|
||||
})) {
|
||||
mutated = true
|
||||
}
|
||||
|
||||
if (report.details?.newPlanetId) {
|
||||
const remappedNewPlanetId = getUpdatedPlanetId(report.details.newPlanetId, idMap, {
|
||||
position: report.targetPosition,
|
||||
planetName: report.details.newPlanetName || report.targetPlanetName
|
||||
})
|
||||
|
||||
if (remappedNewPlanetId) {
|
||||
report.details.newPlanetId = remappedNewPlanetId
|
||||
mutated = true
|
||||
}
|
||||
}
|
||||
|
||||
return mutated
|
||||
}
|
||||
|
||||
const fixPlayerPlanetsAndQueues = (player: Player, idMap: DuplicatePlanetIdMap): boolean => {
|
||||
let mutated = false
|
||||
|
||||
player.planets.forEach(planet => {
|
||||
if (planet.isMoon && updateParentPlanetId(planet, idMap, {
|
||||
position: planet.position,
|
||||
isMoon: false
|
||||
})) {
|
||||
mutated = true
|
||||
}
|
||||
|
||||
// 等待队列里的 planetId 应始终与所属星球保持一致
|
||||
planet.waitingBuildQueue?.forEach(item => {
|
||||
if (item.planetId && item.planetId !== planet.id) {
|
||||
item.planetId = planet.id
|
||||
mutated = true
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return mutated
|
||||
}
|
||||
|
||||
const fixPlayerReferences = (
|
||||
player: Player,
|
||||
data: MigratableGameData,
|
||||
idMap: DuplicatePlanetIdMap
|
||||
): boolean => {
|
||||
let mutated = false
|
||||
|
||||
if (updateCurrentPlanetId(data, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
|
||||
player.fleetMissions?.forEach(mission => {
|
||||
if (updateMissionTargetPlanetId(mission, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
})
|
||||
|
||||
player.spyReports?.forEach(report => {
|
||||
if (updateSpyReportTargetPlanetId(report, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
})
|
||||
|
||||
player.spiedNotifications?.forEach(notification => {
|
||||
if (updateSpiedNotificationTargetPlanetId(notification, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
})
|
||||
|
||||
player.npcActivityNotifications?.forEach(notification => {
|
||||
if (updateNPCActivityTargetPlanetId(notification, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
})
|
||||
|
||||
player.missionReports?.forEach(report => {
|
||||
if (updateMissionReportPlanetIds(report, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
})
|
||||
|
||||
player.incomingFleetAlerts?.forEach(alert => {
|
||||
if (updateIncomingAlertTargetPlanetId(alert, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
})
|
||||
|
||||
player.jointAttackInvites?.forEach(invite => {
|
||||
if (updateJointAttackTargetPlanetId(invite, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
})
|
||||
|
||||
player.allyDefenseNotifications?.forEach(notification => {
|
||||
if (updateAllyDefenseTargetPlanetId(notification, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
})
|
||||
|
||||
return mutated
|
||||
}
|
||||
|
||||
const fixNpcPlayerSpyReports = (npc: NPC, idMap: DuplicatePlanetIdMap): boolean => {
|
||||
if (!npc.playerSpyReports) {
|
||||
return false
|
||||
}
|
||||
|
||||
let mutated = false
|
||||
const remappedPlayerSpyReports: Record<string, SpyReport> = {}
|
||||
|
||||
// playerSpyReports 的 key 就是玩家星球 ID,需要和报告内容一起迁移
|
||||
Object.entries(npc.playerSpyReports).forEach(([planetId, report]) => {
|
||||
if (updateSpyReportTargetPlanetId(report, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
|
||||
const remappedPlanetId = getUpdatedPlanetId(planetId, idMap, {
|
||||
position: report.targetPosition,
|
||||
planetName: report.targetPlanetName
|
||||
})
|
||||
|
||||
if (remappedPlanetId) {
|
||||
remappedPlayerSpyReports[remappedPlanetId] = report
|
||||
mutated = true
|
||||
return
|
||||
}
|
||||
|
||||
remappedPlayerSpyReports[planetId] = report
|
||||
})
|
||||
|
||||
npc.playerSpyReports = remappedPlayerSpyReports
|
||||
return mutated
|
||||
}
|
||||
|
||||
const fixNpcReferences = (npcs: NPC[], idMap: DuplicatePlanetIdMap): boolean => {
|
||||
let mutated = false
|
||||
|
||||
npcs.forEach(npc => {
|
||||
if (fixNpcPlayerSpyReports(npc, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
|
||||
npc.fleetMissions?.forEach(mission => {
|
||||
if (updateMissionTargetPlanetId(mission, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return mutated
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复玩家星球的重复ID,并同步更新可被可靠识别的旧引用。
|
||||
* 缺少位置或名称上下文、无法安全判定归属的旧引用会保留原ID,
|
||||
* 继续指向保留下来的首个星球,避免把数据误指到错误目标。
|
||||
*/
|
||||
const fixDuplicatePlanetIds = (data: MigratableGameData): boolean => {
|
||||
const player = data.player
|
||||
if (!player || !Array.isArray(player.planets) || player.planets.length === 0) {
|
||||
return false
|
||||
}
|
||||
|
||||
const idMap = buildDuplicatePlanetIdMap(player)
|
||||
if (idMap.size === 0) {
|
||||
return false
|
||||
}
|
||||
|
||||
// buildDuplicatePlanetIdMap 已经在上一步直接修复了重复星球 ID,
|
||||
// 只要 idMap 非空,就说明当前迁移已经发生了实际修改。
|
||||
let mutated = true
|
||||
|
||||
if (fixPlayerPlanetsAndQueues(player, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
|
||||
if (fixPlayerReferences(player, data, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
|
||||
if (data.npcs && fixNpcReferences(data.npcs, idMap)) {
|
||||
mutated = true
|
||||
}
|
||||
|
||||
return mutated
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行数据迁移
|
||||
* 将旧版本的 universePlanets 和 debrisFields 从 gameStore 迁移到 universeStore
|
||||
@@ -22,13 +544,13 @@ export const migrateGameData = (): void => {
|
||||
if (!oldEncryptedData) return
|
||||
|
||||
// 尝试解密(如果是加密格式)
|
||||
let oldData: any
|
||||
let oldData: MigratableGameData
|
||||
try {
|
||||
oldData = decryptData(oldEncryptedData)
|
||||
oldData = decryptData(oldEncryptedData) as MigratableGameData
|
||||
} catch {
|
||||
// 解密失败,可能是新格式(未加密),直接解析
|
||||
try {
|
||||
oldData = JSON.parse(oldEncryptedData)
|
||||
oldData = JSON.parse(oldEncryptedData) as MigratableGameData
|
||||
} catch {
|
||||
return // 无法解析,放弃迁移
|
||||
}
|
||||
@@ -100,6 +622,11 @@ export const migrateGameData = (): void => {
|
||||
needsSave = true
|
||||
}
|
||||
|
||||
// 修复重复的星球ID
|
||||
if (fixDuplicatePlanetIds(oldData)) {
|
||||
needsSave = true
|
||||
}
|
||||
|
||||
// 迁移温度数据:为没有温度的星球生成温度
|
||||
// 玩家星球
|
||||
if (oldData.player?.planets && Array.isArray(oldData.player.planets)) {
|
||||
@@ -164,10 +691,11 @@ export const migrateGameData = (): void => {
|
||||
// 新版本统一使用 npc.relations[playerId] 存储NPC对玩家的关系
|
||||
if (oldData.player?.diplomaticRelations && oldData.npcs && Array.isArray(oldData.npcs)) {
|
||||
const playerId = oldData.player.id
|
||||
const npcs = oldData.npcs
|
||||
const playerRelations = oldData.player.diplomaticRelations as Record<string, any>
|
||||
|
||||
Object.entries(playerRelations).forEach(([npcId, relation]) => {
|
||||
const npc = oldData.npcs.find((n: NPC) => n.id === npcId)
|
||||
const npc = npcs.find((n: NPC) => n.id === npcId)
|
||||
if (npc) {
|
||||
if (!npc.relations) {
|
||||
npc.relations = {}
|
||||
|
||||
@@ -190,6 +190,7 @@
|
||||
import * as publicLogic from '@/logic/publicLogic'
|
||||
import * as shipValidation from '@/logic/shipValidation'
|
||||
import * as shipLogic from '@/logic/shipLogic'
|
||||
import * as missileLogic from '@/logic/missileLogic'
|
||||
import * as gameLogic from '@/logic/gameLogic'
|
||||
import * as waitingQueueLogic from '@/logic/waitingQueueLogic'
|
||||
import * as officerLogic from '@/logic/officerLogic'
|
||||
@@ -204,12 +205,12 @@
|
||||
// 导弹容量相关计算
|
||||
const missileSiloCapacity = computed(() => {
|
||||
if (!planet.value) return 0
|
||||
return shipLogic.calculateMissileSiloCapacity(planet.value.buildings)
|
||||
return missileLogic.calculateMissileSiloCapacity(planet.value.buildings)
|
||||
})
|
||||
|
||||
const currentMissileCount = computed(() => {
|
||||
if (!planet.value) return 0
|
||||
return shipLogic.calculateCurrentMissileCount(planet.value.defense)
|
||||
return missileLogic.calculateCurrentMissileCount(planet.value.defense)
|
||||
})
|
||||
|
||||
// AlertDialog 状态
|
||||
|
||||
@@ -181,12 +181,39 @@
|
||||
</ScrollableDialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- 搜索和排序工具栏 -->
|
||||
<div class="flex flex-col sm:flex-row gap-4">
|
||||
<!-- 搜索框 -->
|
||||
<div class="relative">
|
||||
<div class="relative flex-1">
|
||||
<Search class="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input v-model="searchQuery" type="text" :placeholder="t('diplomacy.searchPlaceholder')" class="pl-10" />
|
||||
</div>
|
||||
|
||||
<!-- 排序控制 -->
|
||||
<div class="flex gap-2">
|
||||
<Select v-model="sortBy">
|
||||
<SelectTrigger class="w-[140px]">
|
||||
<SelectValue :placeholder="t('diplomacy.sort.label')" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="reputation">{{ t('diplomacy.sort.reputation') }}</SelectItem>
|
||||
<SelectItem value="planets">{{ t('diplomacy.sort.planets') }}</SelectItem>
|
||||
<SelectItem value="difficulty">{{ t('diplomacy.sort.difficulty') }}</SelectItem>
|
||||
<SelectItem value="allies">{{ t('diplomacy.sort.allies') }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
@click="sortOrder = sortOrder === 'asc' ? 'desc' : 'asc'"
|
||||
:title="sortOrder === 'asc' ? t('diplomacy.sort.ascending') : t('diplomacy.sort.descending')"
|
||||
>
|
||||
<ArrowUpDown class="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 关系状态过滤标签 -->
|
||||
<Tabs v-model="activeTab" class="w-full">
|
||||
<TabsList class="grid w-full grid-cols-4">
|
||||
@@ -379,6 +406,13 @@
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { Dialog, DialogDescription, DialogTitle } from '@/components/ui/dialog'
|
||||
import ScrollableDialogContent from '@/components/ui/dialog/ScrollableDialogContent.vue'
|
||||
import {
|
||||
@@ -393,7 +427,7 @@
|
||||
import NpcRelationCard from '@/components/npc/NpcRelationCard.vue'
|
||||
import NpcRelationRow from '@/components/npc/NpcRelationRow.vue'
|
||||
import { RelationStatus } from '@/types/game'
|
||||
import type { DiplomaticRelation } from '@/types/game'
|
||||
import type { DiplomaticRelation, NPC } from '@/types/game'
|
||||
import * as npcBehaviorLogic from '@/logic/npcBehaviorLogic'
|
||||
import {
|
||||
Search,
|
||||
@@ -403,10 +437,13 @@
|
||||
Swords,
|
||||
Activity,
|
||||
LayoutGrid,
|
||||
List
|
||||
List,
|
||||
ArrowUpDown
|
||||
} from 'lucide-vue-next'
|
||||
import { Empty, EmptyContent, EmptyDescription } from '@/components/ui/empty'
|
||||
|
||||
type NPCSortBy = 'reputation' | 'planets' | 'difficulty' | 'allies'
|
||||
|
||||
const route = useRoute()
|
||||
const gameStore = useGameStore()
|
||||
const npcStore = useNPCStore()
|
||||
@@ -435,6 +472,56 @@
|
||||
// 搜索功能
|
||||
const searchQuery = ref('')
|
||||
|
||||
// 排序状态
|
||||
const sortBy = ref<NPCSortBy>('reputation')
|
||||
const sortOrder = ref<'asc' | 'desc'>('desc')
|
||||
|
||||
const assertNever = (value: never): never => {
|
||||
throw new Error(`Unexpected NPC sort type: ${value}`)
|
||||
}
|
||||
|
||||
// 排序函数
|
||||
const sortNpcs = (npcs: NPC[], predicate: (npc: NPC) => boolean = () => true) => {
|
||||
return npcs.filter(predicate).sort((a, b) => {
|
||||
let valA = 0
|
||||
let valB = 0
|
||||
|
||||
switch (sortBy.value) {
|
||||
case 'reputation':
|
||||
valA = getRelation(a.id)?.reputation || 0
|
||||
valB = getRelation(b.id)?.reputation || 0
|
||||
break
|
||||
case 'planets':
|
||||
valA = a.planets.length
|
||||
valB = b.planets.length
|
||||
break
|
||||
case 'difficulty':
|
||||
// 简单=1, 普通=2, 困难=3
|
||||
// eslint-disable-next-line no-case-declarations
|
||||
const getDifficultyVal = (diff: string) => {
|
||||
if (diff === 'hard') return 3
|
||||
if (diff === 'medium') return 2
|
||||
return 1
|
||||
}
|
||||
valA = a.difficultyLevel || getDifficultyVal(a.difficulty)
|
||||
valB = b.difficultyLevel || getDifficultyVal(b.difficulty)
|
||||
break
|
||||
case 'allies':
|
||||
valA = a.allies?.length || 0
|
||||
valB = b.allies?.length || 0
|
||||
break
|
||||
default:
|
||||
return assertNever(sortBy.value)
|
||||
}
|
||||
|
||||
if (sortOrder.value === 'asc') {
|
||||
return valA - valB
|
||||
} else {
|
||||
return valB - valA
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// NPC诊断功能
|
||||
const npcDiagnosticOpen = ref(false)
|
||||
const npcDiagnostics = ref<npcBehaviorLogic.NPCDiagnosticInfo[]>([])
|
||||
@@ -620,34 +707,34 @@
|
||||
}
|
||||
|
||||
// 搜索过滤函数
|
||||
const matchesSearch = (npc: (typeof npcStore.npcs)[0]) => {
|
||||
const matchesSearch = (npc: NPC) => {
|
||||
if (!searchQuery.value.trim()) return true
|
||||
const query = searchQuery.value.toLowerCase().trim()
|
||||
return npc.name.toLowerCase().includes(query) || npc.id.toLowerCase().includes(query)
|
||||
}
|
||||
|
||||
// 按关系状态分类NPC(同时应用搜索过滤)
|
||||
const allNpcs = computed(() => npcStore.npcs.filter(matchesSearch))
|
||||
// 先统一排序一次,避免不同标签页在同一批数据上重复排序
|
||||
const sortedNpcs = computed(() => sortNpcs(npcStore.npcs, matchesSearch))
|
||||
|
||||
const allNpcs = computed(() => sortedNpcs.value)
|
||||
|
||||
const friendlyNpcs = computed(() => {
|
||||
return npcStore.npcs.filter(npc => {
|
||||
if (!matchesSearch(npc)) return false
|
||||
return sortedNpcs.value.filter(npc => {
|
||||
const relation = getRelation(npc.id)
|
||||
return relation?.status === RelationStatus.Friendly
|
||||
})
|
||||
})
|
||||
|
||||
const neutralNpcs = computed(() => {
|
||||
return npcStore.npcs.filter(npc => {
|
||||
if (!matchesSearch(npc)) return false
|
||||
return sortedNpcs.value.filter(npc => {
|
||||
const relation = getRelation(npc.id)
|
||||
return !relation || relation.status === RelationStatus.Neutral
|
||||
})
|
||||
})
|
||||
|
||||
const hostileNpcs = computed(() => {
|
||||
return npcStore.npcs.filter(npc => {
|
||||
if (!matchesSearch(npc)) return false
|
||||
return sortedNpcs.value.filter(npc => {
|
||||
const relation = getRelation(npc.id)
|
||||
return relation?.status === RelationStatus.Hostile
|
||||
})
|
||||
|
||||
@@ -642,6 +642,7 @@
|
||||
import * as diplomaticLogic from '@/logic/diplomaticLogic'
|
||||
import * as gameLogic from '@/logic/gameLogic'
|
||||
import * as moonLogic from '@/logic/moonLogic'
|
||||
import { generateId } from '@/utils/id'
|
||||
|
||||
const route = useRoute()
|
||||
const gameStore = useGameStore()
|
||||
@@ -934,7 +935,7 @@
|
||||
|
||||
// 生成唯一ID
|
||||
const generatePresetId = (): string => {
|
||||
return `preset_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
|
||||
return generateId('fleet_preset')
|
||||
}
|
||||
|
||||
// 保存当前配置为预设
|
||||
|
||||
@@ -79,6 +79,44 @@
|
||||
|
||||
<!-- 建筑/科技/舰船/防御/军官 - 统一配置渲染 -->
|
||||
<TabsContent v-for="section in gmSections" :key="section.tabValue" :value="section.tabValue" class="space-y-4">
|
||||
<!-- 预设操作区 -->
|
||||
<Card v-if="isPresettableSection(section)" class="mb-4">
|
||||
<CardHeader class="pb-3">
|
||||
<CardTitle class="text-lg">{{ t('gmView.presets') || 'Presets' }}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div class="flex flex-col sm:flex-row gap-4 items-end sm:items-center">
|
||||
<div class="flex gap-2 w-full sm:w-auto">
|
||||
<Select v-model="selectedPresets[section.tabValue]">
|
||||
<SelectTrigger class="w-[200px]">
|
||||
<SelectValue :placeholder="t('gmView.choosePreset') || 'Choose Preset'" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="default">{{ t('gmView.defaultPreset') || 'Default Preset' }}</SelectItem>
|
||||
<SelectItem v-for="p in customPresets[section.tabValue]" :key="p.id" :value="p.id">
|
||||
{{ p.name }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button @click="handleApplyPreset(section)">{{ t('gmView.applyPreset') || 'Apply' }}</Button>
|
||||
<Button
|
||||
v-if="selectedPresets[section.tabValue] !== 'default'"
|
||||
@click="handleDeletePreset(section)"
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
:title="t('gmView.deletePreset') || 'Delete Preset'"
|
||||
>
|
||||
<Trash2 class="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div class="flex gap-2 w-full sm:w-auto ml-auto">
|
||||
<Input v-model="presetNames[section.tabValue]" :placeholder="t('gmView.presetName') || 'Preset Name'" class="w-[150px]" />
|
||||
<Button @click="handleSavePreset(section)" variant="outline">{{ t('gmView.savePreset') || 'Save' }}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{{ t(section.titleKey) }}</CardTitle>
|
||||
@@ -213,6 +251,22 @@
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<!-- 预设覆盖确认对话框 -->
|
||||
<AlertDialog :open="presetOverwriteDialogOpen" @update:open="presetOverwriteDialogOpen = $event">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{{ t('gmView.confirmOverwriteTitle') || 'Preset Already Exists' }}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{{ t('gmView.confirmOverwriteMessage', { name: pendingPresetToOverwrite?.name || '' }) || `Preset with name "${pendingPresetToOverwrite?.name}" already exists. Overwrite?` }}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel @click="presetOverwriteDialogOpen = false">{{ t('common.cancel') }}</AlertDialogCancel>
|
||||
<AlertDialogAction @click="handleConfirmOverwrite">{{ t('common.confirm') }}</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<!-- AlertDialog 提示对话框 -->
|
||||
<AlertDialog :open="alertDialogOpen" @update:open="alertDialogOpen = $event">
|
||||
<AlertDialogContent>
|
||||
@@ -263,7 +317,286 @@
|
||||
import { BuildingType, TechnologyType, ShipType, DefenseType, OfficerType } from '@/types/game'
|
||||
import * as npcBehaviorLogic from '@/logic/npcBehaviorLogic'
|
||||
import * as publicLogic from '@/logic/publicLogic'
|
||||
import { Home } from 'lucide-vue-next'
|
||||
import { calculateMaxFleetStorage } from '@/logic/fleetStorageLogic'
|
||||
import { calculateMissileSiloCapacity } from '@/logic/missileLogic'
|
||||
import { generateId } from '@/utils/id'
|
||||
import { Home, Trash2 } from 'lucide-vue-next'
|
||||
|
||||
// --- 预设系统 ---
|
||||
interface GMPreset {
|
||||
id: string
|
||||
name: string
|
||||
values: Record<string, number>
|
||||
}
|
||||
|
||||
type GMSectionTabValue = 'buildings' | 'research' | 'ships' | 'defense' | 'officers'
|
||||
type GMPresetSectionKey = Exclude<GMSectionTabValue, 'officers'>
|
||||
|
||||
type GMSection = {
|
||||
tabValue: GMSectionTabValue
|
||||
titleKey: string
|
||||
descKey: string
|
||||
items: string[]
|
||||
max?: number
|
||||
placeholder?: string
|
||||
buttons: { label: string; value: number }[]
|
||||
getItemName: (item: string) => string
|
||||
getValue: (item: string) => number
|
||||
setValue: (item: string, val: number) => void
|
||||
onButtonClick: (item: string, val: number) => void
|
||||
}
|
||||
|
||||
type GMPresetSection = GMSection & {
|
||||
tabValue: GMPresetSectionKey
|
||||
}
|
||||
|
||||
type GMPresetNameMap = Record<GMPresetSectionKey, string>
|
||||
type GMSelectedPresetMap = Record<GMPresetSectionKey, string>
|
||||
type GMCustomPresetMap = Record<GMPresetSectionKey, GMPreset[]>
|
||||
|
||||
interface PendingPresetOverwrite {
|
||||
section: GMPresetSection
|
||||
name: string
|
||||
values: Record<string, number>
|
||||
existingIndex: number
|
||||
}
|
||||
|
||||
// 校验预设结构,避免历史脏数据污染当前视图
|
||||
const isGMPreset = (value: unknown): value is GMPreset => {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return false
|
||||
}
|
||||
|
||||
const preset = value as Partial<GMPreset>
|
||||
return typeof preset.id === 'string' && typeof preset.name === 'string' && typeof preset.values === 'object' && preset.values !== null
|
||||
}
|
||||
|
||||
// 只有建筑/科技/舰船/防御页支持预设
|
||||
const isPresettableSection = (section: GMSection): section is GMPresetSection => {
|
||||
return section.tabValue !== 'officers'
|
||||
}
|
||||
|
||||
const presetOverwriteDialogOpen = ref(false)
|
||||
const pendingPresetToOverwrite = ref<PendingPresetOverwrite | null>(null)
|
||||
|
||||
const getPresets = (type: GMPresetSectionKey): GMPreset[] => {
|
||||
const key = `gm_presets_${type}`
|
||||
const data = localStorage.getItem(key)
|
||||
if (!data) {
|
||||
return []
|
||||
}
|
||||
|
||||
try {
|
||||
// 兼容旧版本或手动修改导致的损坏数据,避免页面因解析失败崩溃
|
||||
const parsed = JSON.parse(data)
|
||||
if (!Array.isArray(parsed)) {
|
||||
localStorage.removeItem(key)
|
||||
return []
|
||||
}
|
||||
|
||||
const presets = parsed.filter(isGMPreset)
|
||||
// 过滤掉结构不完整的预设,并顺手回写清理后的结果
|
||||
if (presets.length !== parsed.length) {
|
||||
localStorage.setItem(key, JSON.stringify(presets))
|
||||
}
|
||||
|
||||
return presets
|
||||
} catch {
|
||||
localStorage.removeItem(key)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
const savePresets = (type: GMPresetSectionKey, presets: GMPreset[]) => {
|
||||
localStorage.setItem(`gm_presets_${type}`, JSON.stringify(presets))
|
||||
}
|
||||
|
||||
const presetNames = ref<GMPresetNameMap>({
|
||||
buildings: '',
|
||||
research: '',
|
||||
ships: '',
|
||||
defense: ''
|
||||
})
|
||||
|
||||
const selectedPresets = ref<GMSelectedPresetMap>({
|
||||
buildings: 'default',
|
||||
research: 'default',
|
||||
ships: 'default',
|
||||
defense: 'default'
|
||||
})
|
||||
|
||||
const customPresets = ref<GMCustomPresetMap>({
|
||||
buildings: getPresets('buildings'),
|
||||
research: getPresets('research'),
|
||||
ships: getPresets('ships'),
|
||||
defense: getPresets('defense')
|
||||
})
|
||||
|
||||
const handleSavePreset = (section: GMSection) => {
|
||||
if (!isPresettableSection(section)) return
|
||||
|
||||
const name = presetNames.value[section.tabValue]?.trim()
|
||||
if (!name) {
|
||||
toast.error(t('gmView.presetNameRequired') || '请输入预设名称')
|
||||
return
|
||||
}
|
||||
|
||||
const values: Record<string, number> = {}
|
||||
section.items.forEach((item: string) => {
|
||||
values[item] = section.getValue(item)
|
||||
})
|
||||
|
||||
// 检查是否存在同名预设
|
||||
const presets = customPresets.value[section.tabValue]
|
||||
const existingIndex = presets.findIndex(p => p.name === name)
|
||||
|
||||
if (existingIndex !== -1) {
|
||||
pendingPresetToOverwrite.value = {
|
||||
section,
|
||||
name,
|
||||
values,
|
||||
existingIndex
|
||||
}
|
||||
presetOverwriteDialogOpen.value = true
|
||||
return
|
||||
}
|
||||
|
||||
const newPreset: GMPreset = {
|
||||
id: generateId('gm_preset'),
|
||||
name,
|
||||
values
|
||||
}
|
||||
|
||||
presets.push(newPreset)
|
||||
savePresets(section.tabValue, presets)
|
||||
presetNames.value[section.tabValue] = ''
|
||||
selectedPresets.value[section.tabValue] = newPreset.id
|
||||
toast.success(t('gmView.presetSaved') || '预设保存成功')
|
||||
}
|
||||
|
||||
const handleConfirmOverwrite = () => {
|
||||
if (!pendingPresetToOverwrite.value) return
|
||||
|
||||
const { section, values, existingIndex } = pendingPresetToOverwrite.value
|
||||
|
||||
const presets = customPresets.value[section.tabValue]
|
||||
|
||||
if (presets[existingIndex]) {
|
||||
// 更新现有预设的值,保持ID不变
|
||||
presets[existingIndex].values = values
|
||||
|
||||
savePresets(section.tabValue, presets)
|
||||
|
||||
presetNames.value[section.tabValue] = ''
|
||||
selectedPresets.value[section.tabValue] = presets[existingIndex].id
|
||||
|
||||
toast.success(t('gmView.presetSaved') || '预设保存成功')
|
||||
}
|
||||
|
||||
presetOverwriteDialogOpen.value = false
|
||||
pendingPresetToOverwrite.value = null
|
||||
}
|
||||
|
||||
const handleDeletePreset = (section: GMSection) => {
|
||||
if (!isPresettableSection(section)) return
|
||||
|
||||
const presetId = selectedPresets.value[section.tabValue]
|
||||
if (!presetId || presetId === 'default') {
|
||||
toast.error(t('gmView.cannotDeleteDefault') || '无法删除默认预设')
|
||||
return
|
||||
}
|
||||
|
||||
const presets = customPresets.value[section.tabValue]
|
||||
const index = presets.findIndex(p => p.id === presetId)
|
||||
|
||||
if (index !== -1) {
|
||||
presets.splice(index, 1)
|
||||
savePresets(section.tabValue, presets)
|
||||
selectedPresets.value[section.tabValue] = 'default'
|
||||
toast.success(t('gmView.presetDeleted') || '预设已删除')
|
||||
}
|
||||
}
|
||||
|
||||
const handleApplyPreset = (section: GMSection) => {
|
||||
if (!isPresettableSection(section)) return
|
||||
|
||||
const presetId = selectedPresets.value[section.tabValue]
|
||||
if (!presetId) return
|
||||
|
||||
if (presetId === 'default') {
|
||||
if (section.tabValue === 'buildings') {
|
||||
const explicitMax: Record<string, number> = {
|
||||
[BuildingType.NaniteFactory]: 10,
|
||||
[BuildingType.MissileSilo]: 10,
|
||||
[BuildingType.JumpGate]: 5,
|
||||
[BuildingType.PlanetDestroyerFactory]: 3,
|
||||
[BuildingType.GeoResearchStation]: 10,
|
||||
[BuildingType.DeepDrillingFacility]: 10,
|
||||
[BuildingType.University]: 10
|
||||
}
|
||||
section.items.forEach((item: string) => {
|
||||
section.setValue(item, explicitMax[item] || 50)
|
||||
})
|
||||
} else if (section.tabValue === 'research') {
|
||||
const explicitMax: Record<string, number> = {
|
||||
[TechnologyType.ComputerTechnology]: 10,
|
||||
[TechnologyType.GravitonTechnology]: 1,
|
||||
[TechnologyType.PlanetDestructionTech]: 10,
|
||||
[TechnologyType.MiningTechnology]: 15,
|
||||
[TechnologyType.IntergalacticResearchNetwork]: 10,
|
||||
[TechnologyType.MineralResearch]: 20,
|
||||
[TechnologyType.CrystalResearch]: 20,
|
||||
[TechnologyType.FuelResearch]: 20
|
||||
}
|
||||
section.items.forEach((item: string) => {
|
||||
section.setValue(item, explicitMax[item] || 100)
|
||||
})
|
||||
} else if (section.tabValue === 'ships') {
|
||||
if (!selectedPlanet.value) return
|
||||
// 某些过滤场景下舰船列表可能为空,避免平均分配时除以 0
|
||||
if (!section.items.length) return
|
||||
|
||||
// 重新计算最大舰队仓储,确保数据是最新的
|
||||
const maxStorage = calculateMaxFleetStorage(selectedPlanet.value, gameStore.player.technologies)
|
||||
|
||||
// 将总容量平均分配给每种舰船
|
||||
const storagePerShip = maxStorage / section.items.length
|
||||
|
||||
section.items.forEach(item => {
|
||||
const usage = SHIPS.value[item as ShipType]?.storageUsage || 1
|
||||
// 如果 usage 为 0 (如某些特殊单位),则给予一个默认数量,或者跳过
|
||||
if (usage <= 0) {
|
||||
section.setValue(item, 100) // 防止除以0,给予固定值
|
||||
} else {
|
||||
section.setValue(item, Math.floor(storagePerShip / usage))
|
||||
}
|
||||
})
|
||||
} else if (section.tabValue === 'defense') {
|
||||
if (!selectedPlanet.value) return
|
||||
const missileCapacity = calculateMissileSiloCapacity(selectedPlanet.value.buildings)
|
||||
const defaultMissileCount = Math.floor(missileCapacity / 2)
|
||||
|
||||
section.items.forEach((item: string) => {
|
||||
// 两种导弹都占用1格空间,默认各分配一半容量
|
||||
if (item === DefenseType.AntiBallisticMissile || item === DefenseType.InterplanetaryMissile) {
|
||||
section.setValue(item, defaultMissileCount)
|
||||
} else {
|
||||
section.setValue(item, 10000)
|
||||
}
|
||||
})
|
||||
}
|
||||
toast.success(t('gmView.presetApplied') || '默认预设应用成功')
|
||||
} else {
|
||||
const customPreset = customPresets.value[section.tabValue].find((p: GMPreset) => p.id === presetId)
|
||||
if (customPreset) {
|
||||
Object.entries(customPreset.values).forEach(([k, v]) => {
|
||||
section.setValue(k, v as number)
|
||||
})
|
||||
toast.success(t('gmView.presetApplied') || '预设应用成功')
|
||||
}
|
||||
}
|
||||
}
|
||||
// --- 预设系统结束 ---
|
||||
|
||||
const router = useRouter()
|
||||
const gameStore = useGameStore()
|
||||
@@ -281,7 +614,8 @@
|
||||
router.push('/')
|
||||
}
|
||||
|
||||
const selectedPlanetId = ref<string>(gameStore.player.planets[0]?.id || '')
|
||||
// 默认选中当前正在游玩的星球
|
||||
const selectedPlanetId = ref<string>(gameStore.currentPlanetId || gameStore.player.planets[0]?.id || '')
|
||||
const officerDays = ref<Record<OfficerType, number>>({} as Record<OfficerType, number>)
|
||||
const selectedNPCId = ref<string>(npcStore.npcs[0]?.id || '')
|
||||
const targetPlanetIndex = ref<string>('0')
|
||||
@@ -336,22 +670,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
// GM编辑区块配置 - 统一管理建筑/科技/舰船/防御/军官
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type GMSection = {
|
||||
tabValue: string
|
||||
titleKey: string
|
||||
descKey: string
|
||||
items: string[]
|
||||
max?: number
|
||||
placeholder?: string
|
||||
buttons: { label: string; value: number }[]
|
||||
getItemName: (item: any) => string
|
||||
getValue: (item: any) => number
|
||||
setValue: (item: any, val: number) => void
|
||||
onButtonClick: (item: any, val: number) => void
|
||||
}
|
||||
|
||||
const gmSections = computed<GMSection[]>(() => [
|
||||
{
|
||||
tabValue: 'buildings',
|
||||
@@ -364,17 +682,17 @@
|
||||
{ label: 'Lv 10', value: 10 },
|
||||
{ label: 'Lv 30', value: 30 }
|
||||
],
|
||||
getItemName: (item: BuildingType) => BUILDINGS.value[item].name,
|
||||
getValue: (item: BuildingType) => selectedPlanet.value?.buildings[item] || 0,
|
||||
setValue: (item: BuildingType, val: number) => {
|
||||
getItemName: item => BUILDINGS.value[item as BuildingType].name,
|
||||
getValue: item => selectedPlanet.value?.buildings[item as BuildingType] || 0,
|
||||
setValue: (item, val) => {
|
||||
if (selectedPlanet.value) {
|
||||
selectedPlanet.value.buildings[item] = val
|
||||
selectedPlanet.value.buildings[item as BuildingType] = val
|
||||
updatePlayerPoints()
|
||||
}
|
||||
},
|
||||
onButtonClick: (item: BuildingType, val: number) => {
|
||||
onButtonClick: (item, val) => {
|
||||
if (selectedPlanet.value) {
|
||||
selectedPlanet.value.buildings[item] = val
|
||||
selectedPlanet.value.buildings[item as BuildingType] = val
|
||||
updatePlayerPoints()
|
||||
}
|
||||
}
|
||||
@@ -390,14 +708,14 @@
|
||||
{ label: 'Lv 10', value: 10 },
|
||||
{ label: 'Lv 20', value: 20 }
|
||||
],
|
||||
getItemName: (item: TechnologyType) => TECHNOLOGIES.value[item].name,
|
||||
getValue: (item: TechnologyType) => gameStore.player.technologies[item] || 0,
|
||||
setValue: (item: TechnologyType, val: number) => {
|
||||
gameStore.player.technologies[item] = val
|
||||
getItemName: item => TECHNOLOGIES.value[item as TechnologyType].name,
|
||||
getValue: item => gameStore.player.technologies[item as TechnologyType] || 0,
|
||||
setValue: (item, val) => {
|
||||
gameStore.player.technologies[item as TechnologyType] = val
|
||||
updatePlayerPoints()
|
||||
},
|
||||
onButtonClick: (item: TechnologyType, val: number) => {
|
||||
gameStore.player.technologies[item] = val
|
||||
onButtonClick: (item, val) => {
|
||||
gameStore.player.technologies[item as TechnologyType] = val
|
||||
updatePlayerPoints()
|
||||
}
|
||||
},
|
||||
@@ -412,17 +730,17 @@
|
||||
{ label: '+100', value: 100 },
|
||||
{ label: '+1K', value: 1000 }
|
||||
],
|
||||
getItemName: (item: ShipType) => SHIPS.value[item].name,
|
||||
getValue: (item: ShipType) => selectedPlanet.value?.fleet[item] || 0,
|
||||
setValue: (item: ShipType, val: number) => {
|
||||
getItemName: item => SHIPS.value[item as ShipType].name,
|
||||
getValue: item => selectedPlanet.value?.fleet[item as ShipType] || 0,
|
||||
setValue: (item, val) => {
|
||||
if (selectedPlanet.value) {
|
||||
selectedPlanet.value.fleet[item] = val
|
||||
selectedPlanet.value.fleet[item as ShipType] = val
|
||||
updatePlayerPoints()
|
||||
}
|
||||
},
|
||||
onButtonClick: (item: ShipType, val: number) => {
|
||||
onButtonClick: (item, val) => {
|
||||
if (selectedPlanet.value) {
|
||||
selectedPlanet.value.fleet[item] = (selectedPlanet.value.fleet[item] || 0) + val
|
||||
selectedPlanet.value.fleet[item as ShipType] = (selectedPlanet.value.fleet[item as ShipType] || 0) + val
|
||||
updatePlayerPoints()
|
||||
}
|
||||
}
|
||||
@@ -438,17 +756,17 @@
|
||||
{ label: '+100', value: 100 },
|
||||
{ label: '+1K', value: 1000 }
|
||||
],
|
||||
getItemName: (item: DefenseType) => DEFENSES.value[item].name,
|
||||
getValue: (item: DefenseType) => selectedPlanet.value?.defense[item] || 0,
|
||||
setValue: (item: DefenseType, val: number) => {
|
||||
getItemName: item => DEFENSES.value[item as DefenseType].name,
|
||||
getValue: item => selectedPlanet.value?.defense[item as DefenseType] || 0,
|
||||
setValue: (item, val) => {
|
||||
if (selectedPlanet.value) {
|
||||
selectedPlanet.value.defense[item] = val
|
||||
selectedPlanet.value.defense[item as DefenseType] = val
|
||||
updatePlayerPoints()
|
||||
}
|
||||
},
|
||||
onButtonClick: (item: DefenseType, val: number) => {
|
||||
onButtonClick: (item, val) => {
|
||||
if (selectedPlanet.value) {
|
||||
selectedPlanet.value.defense[item] = (selectedPlanet.value.defense[item] || 0) + val
|
||||
selectedPlanet.value.defense[item as DefenseType] = (selectedPlanet.value.defense[item as DefenseType] || 0) + val
|
||||
updatePlayerPoints()
|
||||
}
|
||||
}
|
||||
@@ -465,27 +783,28 @@
|
||||
{ label: `30${t('gmView.days')}`, value: 30 },
|
||||
{ label: `365${t('gmView.days')}`, value: 365 }
|
||||
],
|
||||
getItemName: (item: OfficerType) => OFFICERS.value[item].name,
|
||||
getValue: (item: OfficerType) => officerDays.value[item] || 0,
|
||||
setValue: (item: OfficerType, val: number) => {
|
||||
officerDays.value[item] = val
|
||||
getItemName: item => OFFICERS.value[item as OfficerType].name,
|
||||
getValue: item => officerDays.value[item as OfficerType] || 0,
|
||||
setValue: (item, val) => {
|
||||
officerDays.value[item as OfficerType] = val
|
||||
},
|
||||
onButtonClick: (item: OfficerType, days: number) => {
|
||||
officerDays.value[item] = days
|
||||
onButtonClick: (item, days) => {
|
||||
const officerType = item as OfficerType
|
||||
officerDays.value[officerType] = days
|
||||
const now = Date.now()
|
||||
const expiresAt = now + days * 24 * 60 * 60 * 1000
|
||||
if (!gameStore.player.officers[item]) {
|
||||
gameStore.player.officers[item] = {
|
||||
type: item,
|
||||
if (!gameStore.player.officers[officerType]) {
|
||||
gameStore.player.officers[officerType] = {
|
||||
type: officerType,
|
||||
active: true,
|
||||
hiredAt: now,
|
||||
expiresAt: expiresAt
|
||||
}
|
||||
} else {
|
||||
gameStore.player.officers[item].expiresAt = expiresAt
|
||||
gameStore.player.officers[item].active = true
|
||||
if (!gameStore.player.officers[item].hiredAt) {
|
||||
gameStore.player.officers[item].hiredAt = now
|
||||
gameStore.player.officers[officerType].expiresAt = expiresAt
|
||||
gameStore.player.officers[officerType].active = true
|
||||
if (!gameStore.player.officers[officerType].hiredAt) {
|
||||
gameStore.player.officers[officerType].hiredAt = now
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -659,11 +978,13 @@
|
||||
const maxAllResources = () => {
|
||||
if (!selectedPlanet.value) return
|
||||
|
||||
const maxAmount = 1000000000000000000
|
||||
selectedPlanet.value.resources.metal = maxAmount
|
||||
selectedPlanet.value.resources.crystal = maxAmount
|
||||
selectedPlanet.value.resources.deuterium = maxAmount
|
||||
selectedPlanet.value.resources.darkMatter = maxAmount
|
||||
// 计算当前星球的资源存储上限
|
||||
const capacity = publicLogic.getResourceCapacity(selectedPlanet.value, gameStore.player.officers)
|
||||
|
||||
selectedPlanet.value.resources.metal = capacity.metal
|
||||
selectedPlanet.value.resources.crystal = capacity.crystal
|
||||
selectedPlanet.value.resources.deuterium = capacity.deuterium
|
||||
selectedPlanet.value.resources.darkMatter = capacity.darkMatter
|
||||
|
||||
toast.success(t('gmView.maxAllResourcesSuccess'))
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
<p class="text-sm text-muted-foreground">{{ t('settings.importDataDesc') }}</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<input ref="fileInputRef" type="file" accept=".json" class="hidden" @change="handleFileSelect" />
|
||||
<input ref="fileInputRef" type="file" accept=".json,application/json,text/plain" class="hidden" @change="handleFileSelect" />
|
||||
<Button @click="triggerFileInput" variant="outline">
|
||||
<Upload class="mr-2 h-4 w-4" />
|
||||
{{ t('settings.selectFile') }}
|
||||
@@ -389,6 +389,7 @@
|
||||
import { saveAs } from 'file-saver'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Capacitor } from '@capacitor/core'
|
||||
import { decryptData, encryptData } from '@/utils/crypto'
|
||||
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem'
|
||||
import pkg from '../../package.json'
|
||||
import { checkLatestVersion, canCheckVersion } from '@/utils/versionCheck'
|
||||
@@ -590,18 +591,12 @@
|
||||
const fileName = `${pkg.name}-${new Date().toISOString().slice(0, 10)}-${Date.now()}.json`
|
||||
const jsonString = JSON.stringify(exportData, null, 2)
|
||||
|
||||
// Android 保存到公共 Downloads 目录
|
||||
// Android/原生平台
|
||||
if (Capacitor.isNativePlatform()) {
|
||||
// 检查并请求存储权限
|
||||
// 尝试保存到公共 Downloads 目录
|
||||
try {
|
||||
const permStatus = await Filesystem.checkPermissions()
|
||||
if (permStatus.publicStorage !== 'granted') {
|
||||
const reqResult = await Filesystem.requestPermissions()
|
||||
if (reqResult.publicStorage !== 'granted') {
|
||||
toast.error(t('settings.storagePermissionDenied'))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (permStatus.publicStorage === 'granted') {
|
||||
const result = await Filesystem.writeFile({
|
||||
path: `Download/${fileName}`,
|
||||
data: jsonString,
|
||||
@@ -610,11 +605,78 @@
|
||||
})
|
||||
toast.success(t('settings.exportSuccessWithPath', { path: result.uri }))
|
||||
return
|
||||
}
|
||||
|
||||
// 尝试请求权限
|
||||
const reqResult = await Filesystem.requestPermissions()
|
||||
if (reqResult.publicStorage === 'granted') {
|
||||
const result = await Filesystem.writeFile({
|
||||
path: `Download/${fileName}`,
|
||||
data: jsonString,
|
||||
directory: Directory.ExternalStorage,
|
||||
encoding: Encoding.UTF8
|
||||
})
|
||||
toast.success(t('settings.exportSuccessWithPath', { path: result.uri }))
|
||||
return
|
||||
}
|
||||
} catch (extError) {
|
||||
console.warn('ExternalStorage failed, trying Documents:', extError)
|
||||
}
|
||||
|
||||
// 备选方案:保存到应用文档目录 (TapPlay 等沙盒环境)
|
||||
try {
|
||||
const result = await Filesystem.writeFile({
|
||||
path: fileName,
|
||||
data: jsonString,
|
||||
directory: Directory.Documents,
|
||||
encoding: Encoding.UTF8
|
||||
})
|
||||
toast.success(t('settings.exportSuccessWithPath', { path: result.uri }))
|
||||
return
|
||||
} catch (docError) {
|
||||
console.warn('Documents failed, trying Data:', docError)
|
||||
}
|
||||
|
||||
// 最后备选:保存到应用数据目录
|
||||
try {
|
||||
const result = await Filesystem.writeFile({
|
||||
path: fileName,
|
||||
data: jsonString,
|
||||
directory: Directory.Data,
|
||||
encoding: Encoding.UTF8
|
||||
})
|
||||
toast.success(t('settings.exportSuccessWithPath', { path: result.uri }))
|
||||
return
|
||||
} catch (dataError) {
|
||||
console.warn('Data directory failed:', dataError)
|
||||
}
|
||||
|
||||
// 所有文件系统方式都失败,尝试 Web Share API
|
||||
if (navigator.share && navigator.canShare) {
|
||||
const file = new File([jsonString], fileName, { type: 'application/json' })
|
||||
if (navigator.canShare({ files: [file] })) {
|
||||
await navigator.share({
|
||||
files: [file],
|
||||
title: t('settings.exportData')
|
||||
})
|
||||
toast.success(t('settings.exportSuccess'))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 最后的备选:复制到剪贴板
|
||||
try {
|
||||
await navigator.clipboard.writeText(jsonString)
|
||||
toast.success(t('settings.exportCopiedToClipboard'))
|
||||
return
|
||||
} catch {
|
||||
toast.error(t('settings.exportFailed'))
|
||||
}
|
||||
} else {
|
||||
// Web 使用 file-saver
|
||||
saveAs(new Blob([jsonString], { type: 'application/json' }), fileName)
|
||||
}
|
||||
toast.success(t('settings.exportSuccess'))
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Export failed:', error)
|
||||
toast.error(t('settings.exportFailed'))
|
||||
@@ -649,6 +711,15 @@
|
||||
if (typeof result === 'string') {
|
||||
const importData = JSON.parse(result)
|
||||
|
||||
if (importData.data) {
|
||||
const data = decryptData(importData.data)
|
||||
localStorage.setItem(pkg.name, encryptData(data.game))
|
||||
localStorage.setItem(`${pkg.name}-universe`, encryptData(data.universe))
|
||||
localStorage.setItem(`${pkg.name}-npcs`, encryptData(data.npcs))
|
||||
setTimeout(() => window.location.reload(), 1000)
|
||||
return
|
||||
}
|
||||
|
||||
// 兼容旧版本:如果是旧格式(直接是字符串),只导入游戏数据
|
||||
if (typeof importData === 'string' || !importData.game) {
|
||||
localStorage.setItem(pkg.name, result)
|
||||
|
||||
Reference in New Issue
Block a user