refactor web

This commit is contained in:
bridge
2025-11-20 22:16:27 +08:00
parent cdc3322ff0
commit 10d571e6bb
17 changed files with 947 additions and 155 deletions

View File

@@ -186,11 +186,29 @@ If you like this project, consider starring it~ You can also watch intro videos
```
For supported models, refer to [litellm documentation](https://docs.litellm.ai/docs/providers)
4. Run the simulator:
4. Run the simulator (Local Pygame version):
```bash
python -m src.run.run
```
5. Run Web version (WIP):
Start both backend and frontend.
**Backend:**
```bash
# In project root
python src/server/main.py
```
**Frontend:**
```bash
# In a new terminal, inside 'web' directory
cd web
npm run dev
```
Then visit http://localhost:5173
## Contributors
- Aku, for world design & discussion

View File

@@ -189,11 +189,29 @@
```
具体支持的模型请参考 [litellm文档](https://docs.litellm.ai/docs/providers)
4. 运行模拟器:
4. 运行模拟器(本地 Pygame 版)
```bash
python -m src.run.run
```
5. 运行 Web 版本(开发中):
需要同时启动后端和前端。
**后端:**
```bash
# 在项目根目录
python src/server/main.py
```
**前端:**
```bash
# 打开新终端,进入 web 目录
cd web
npm run dev
```
然后访问 http://localhost:5173
## 贡献者
- Aku, 世界观\玩法设计与讨论

BIN
assets/females/16.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

View File

@@ -2,8 +2,9 @@ import sys
import os
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import uvicorn
# 确保可以导入 src 模块
@@ -24,6 +25,29 @@ game_instance = {
"sim": None
}
class ConnectionManager:
def __init__(self):
self.active_connections: list[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def broadcast(self, message: dict):
import json
try:
# 简单序列化,实际生产可能需要更复杂的 Encoder
txt = json.dumps(message, default=str)
for connection in self.active_connections:
await connection.send_text(txt)
except Exception as e:
print(f"Broadcast error: {e}")
manager = ConnectionManager()
def init_game():
"""初始化游戏世界,逻辑复用自 src/run/run.py"""
print("正在初始化游戏世界...")
@@ -54,10 +78,47 @@ def init_game():
game_instance["sim"] = sim
print("游戏世界初始化完成!")
async def game_loop():
"""后台自动运行游戏循环"""
print("后台游戏循环已启动...")
while True:
# 控制游戏速度,例如每秒 1 次更新
await asyncio.sleep(1.0)
try:
sim = game_instance.get("sim")
world = game_instance.get("world")
if sim and world:
# 执行一步
events = await sim.step()
# 构造广播数据包
state = {
"type": "tick",
"year": int(world.month_stamp.get_year()),
"month": world.month_stamp.get_month().value,
"events": [str(e) for e in events],
# 暂时只发前 50 个角色的位置更新,减少数据量
"avatars": [
{
"id": str(a.id),
"x": int(getattr(a, "pos_x", 0)),
"y": int(getattr(a, "pos_y", 0))
}
for a in list(world.avatar_manager.avatars.values())[:50]
]
}
await manager.broadcast(state)
except Exception as e:
print(f"Game loop error: {e}")
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时初始化
init_game()
# 启动后台任务
asyncio.create_task(game_loop())
yield
# 关闭时清理(如果需要)
@@ -72,10 +133,33 @@ app.add_middleware(
allow_headers=["*"],
)
# 挂载静态资源
ASSETS_PATH = os.path.join(os.path.dirname(__file__), '..', '..', 'assets')
if os.path.exists(ASSETS_PATH):
app.mount("/assets", StaticFiles(directory=ASSETS_PATH), name="assets")
else:
print(f"Warning: Assets path not found: {ASSETS_PATH}")
@app.get("/")
def read_root():
return {"status": "online", "app": "Cultivation World Simulator Backend"}
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await manager.connect(websocket)
try:
while True:
# 保持连接活跃,接收客户端指令(目前暂不处理复杂指令)
data = await websocket.receive_text()
# echo test
if data == "ping":
await websocket.send_text('{"type":"pong"}')
except WebSocketDisconnect:
manager.disconnect(websocket)
except Exception as e:
print(f"WS Error: {e}")
manager.disconnect(websocket)
@app.get("/api/state")
def get_state():
"""获取当前世界的一个快照(调试模式)"""
@@ -121,7 +205,9 @@ def get_state():
"name": aname,
"x": ax,
"y": ay,
"action": str(aaction)
"action": str(aaction),
"gender": str(a.gender.value),
"pic_id": (hash(a.id) % 15) + 1
})
except Exception as e:
return {"step": 3, "error": str(e)}
@@ -137,6 +223,48 @@ def get_state():
except Exception as e:
return {"step": 0, "error": "Fatal: " + str(e)}
@app.get("/api/map")
def get_map():
"""获取静态地图数据(仅需加载一次)"""
world = game_instance.get("world")
if not world or not world.map:
return {"error": "No map"}
# 构造二维数组
w, h = world.map.width, world.map.height
map_data = []
for y in range(h):
row = []
for x in range(w):
tile = world.map.get_tile(x, y)
row.append(tile.type.name)
map_data.append(row)
# 构造区域列表
regions_data = []
if world.map and hasattr(world.map, 'regions'):
for r in world.map.regions.values():
# 确保有中心点
if hasattr(r, 'center_loc') and r.center_loc:
rtype = "unknown"
if hasattr(r, 'get_region_type'):
rtype = r.get_region_type()
regions_data.append({
"id": r.id,
"name": r.name,
"type": rtype,
"x": r.center_loc[0],
"y": r.center_loc[1]
})
return {
"width": w,
"height": h,
"data": map_data,
"regions": regions_data
}
@app.post("/api/step")
async def step_world():
"""手动触发一帧(一个月)"""

185
web/package-lock.json generated
View File

@@ -8,10 +8,13 @@
"name": "web",
"version": "0.0.0",
"dependencies": {
"@vueuse/core": "^14.0.0",
"naive-ui": "^2.43.2",
"pinia": "^3.0.4",
"pixi-viewport": "^6.0.3",
"pixi.js": "^8.14.2",
"vfonts": "^0.0.3"
"vfonts": "^0.0.3",
"vue3-pixi": "^1.0.0-beta.3"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.4",
@@ -20,6 +23,15 @@
"vite": "^5.4.21"
}
},
"node_modules/@antfu/utils": {
"version": "0.7.10",
"resolved": "https://registry.npmjs.org/@antfu/utils/-/utils-0.7.10.tgz",
"integrity": "sha512-+562v9k4aI80m1+VuMHehNJWLOFjBnXn3tdOitzD0il5b7smkSBal4+a3oKiQTbrwMmN/TBUMDvbdoWDehgOww==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
@@ -1141,6 +1153,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/gradient-parser": {
"version": "0.1.5",
"resolved": "https://registry.npmjs.org/@types/gradient-parser/-/gradient-parser-0.1.5.tgz",
"integrity": "sha512-r7K3NkJz3A95WkVVmjs0NcchhHstC2C/VIYNX4JC6tieviUNo774FFeOHjThr3Vw/WCeMP9kAT77MKbIRlO/4w==",
"license": "MIT"
},
"node_modules/@types/katex": {
"version": "0.16.7",
"resolved": "https://registry.npmjs.org/@types/katex/-/katex-0.16.7.tgz",
@@ -1162,6 +1180,12 @@
"@types/lodash": "*"
}
},
"node_modules/@types/web-bluetooth": {
"version": "0.0.21",
"resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz",
"integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==",
"license": "MIT"
},
"node_modules/@vitejs/plugin-vue": {
"version": "5.2.4",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz",
@@ -1318,6 +1342,44 @@
"license": "MIT",
"peer": true
},
"node_modules/@vueuse/core": {
"version": "14.0.0",
"resolved": "https://registry.npmjs.org/@vueuse/core/-/core-14.0.0.tgz",
"integrity": "sha512-d6tKRWkZE8IQElX2aHBxXOMD478fHIYV+Dzm2y9Ag122ICBpNKtGICiXKOhWU3L1kKdttDD9dCMS4bGP3jhCTQ==",
"license": "MIT",
"dependencies": {
"@types/web-bluetooth": "^0.0.21",
"@vueuse/metadata": "14.0.0",
"@vueuse/shared": "14.0.0"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"vue": "^3.5.0"
}
},
"node_modules/@vueuse/metadata": {
"version": "14.0.0",
"resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-14.0.0.tgz",
"integrity": "sha512-6yoGqbJcMldVCevkFiHDBTB1V5Hq+G/haPlGIuaFZHpXC0HADB0EN1ryQAAceiW+ryS3niUwvdFbGiqHqBrfVA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/@vueuse/shared": {
"version": "14.0.0",
"resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-14.0.0.tgz",
"integrity": "sha512-mTCA0uczBgurRlwVaQHfG0Ja7UdGe4g9mwffiJmvLiTtp1G4AQyIjej6si/k8c8pUwTfVpNufck+23gXptPAkw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"vue": "^3.5.0"
}
},
"node_modules/@webgpu/types": {
"version": "0.1.66",
"resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.66.tgz",
@@ -1797,6 +1859,27 @@
}
}
},
"node_modules/pixi-filters": {
"version": "6.1.4",
"resolved": "https://registry.npmjs.org/pixi-filters/-/pixi-filters-6.1.4.tgz",
"integrity": "sha512-6QdkhR8hZ/jXyV7GZG8R0UKkRy9jPeZsOnHaQiKSFEe4tGJ4PfUG90vaC9eyi7g+YKxhKLpNOXu6tmO1+R2tpQ==",
"license": "MIT",
"dependencies": {
"@types/gradient-parser": "^0.1.2"
},
"peerDependencies": {
"pixi.js": ">=8.0.0-0"
}
},
"node_modules/pixi-viewport": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/pixi-viewport/-/pixi-viewport-6.0.3.tgz",
"integrity": "sha512-2+qPJ0/n+8hQYhWvY+795+x9y3MiUrCOWacK0DY53whowWaGdx9iDocy7z1pBwjkZhC52YvrJQuZKK0sdVLtBw==",
"license": "MIT",
"peerDependencies": {
"pixi.js": ">=8"
}
},
"node_modules/pixi.js": {
"version": "8.14.2",
"resolved": "https://registry.npmjs.org/pixi.js/-/pixi.js-8.14.2.tgz",
@@ -2122,6 +2205,106 @@
}
}
},
"node_modules/vue3-pixi": {
"version": "1.0.0-beta.3",
"resolved": "https://registry.npmjs.org/vue3-pixi/-/vue3-pixi-1.0.0-beta.3.tgz",
"integrity": "sha512-WHDA7/VPwAGTnwPSQTxcwTOOjspjX8vh8P3Lgfrg6o2lI4mcjGmHlKiKIZabwlNYqmyr+PZKdnUtjzN/h/0e0w==",
"license": "MIT",
"dependencies": {
"@antfu/utils": "^0.7.10",
"@vueuse/core": "^10.11.1",
"nanoid": "^4.0.2",
"pixi-filters": "^6.1.3",
"pixi.js": "^8.11.0",
"vue-demi": "^0.14.10"
}
},
"node_modules/vue3-pixi/node_modules/@types/web-bluetooth": {
"version": "0.0.20",
"resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.20.tgz",
"integrity": "sha512-g9gZnnXVq7gM7v3tJCWV/qw7w+KeOlSHAhgF9RytFyifW6AF61hdT2ucrYhPq9hLs5JIryeupHV3qGk95dH9ow==",
"license": "MIT"
},
"node_modules/vue3-pixi/node_modules/@vueuse/core": {
"version": "10.11.1",
"resolved": "https://registry.npmjs.org/@vueuse/core/-/core-10.11.1.tgz",
"integrity": "sha512-guoy26JQktXPcz+0n3GukWIy/JDNKti9v6VEMu6kV2sYBsWuGiTU8OWdg+ADfUbHg3/3DlqySDe7JmdHrktiww==",
"license": "MIT",
"dependencies": {
"@types/web-bluetooth": "^0.0.20",
"@vueuse/metadata": "10.11.1",
"@vueuse/shared": "10.11.1",
"vue-demi": ">=0.14.8"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/vue3-pixi/node_modules/@vueuse/metadata": {
"version": "10.11.1",
"resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-10.11.1.tgz",
"integrity": "sha512-IGa5FXd003Ug1qAZmyE8wF3sJ81xGLSqTqtQ6jaVfkeZ4i5kS2mwQF61yhVqojRnenVew5PldLyRgvdl4YYuSw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/vue3-pixi/node_modules/@vueuse/shared": {
"version": "10.11.1",
"resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-10.11.1.tgz",
"integrity": "sha512-LHpC8711VFZlDaYUXEBbFBCQ7GS3dVU9mjOhhMhXP6txTV4EhYQg/KGnQuvt/sPAtoUKq7VVUnL6mVtFoL42sA==",
"license": "MIT",
"dependencies": {
"vue-demi": ">=0.14.8"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/vue3-pixi/node_modules/nanoid": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-4.0.2.tgz",
"integrity": "sha512-7ZtY5KTCNheRGfEFxnedV5zFiORN1+Y1N6zvPTnHQd8ENUvfaDBeuJDZb2bN/oXwXxu3qkTXDzy57W5vAmDTBw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.js"
},
"engines": {
"node": "^14 || ^16 || >=18"
}
},
"node_modules/vue3-pixi/node_modules/vue-demi": {
"version": "0.14.10",
"resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz",
"integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==",
"hasInstallScript": true,
"license": "MIT",
"bin": {
"vue-demi-fix": "bin/vue-demi-fix.js",
"vue-demi-switch": "bin/vue-demi-switch.js"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"@vue/composition-api": "^1.0.0-rc.1",
"vue": "^3.0.0-0 || ^2.6.0"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
}
},
"node_modules/vueuc": {
"version": "0.4.65",
"resolved": "https://registry.npmjs.org/vueuc/-/vueuc-0.4.65.tgz",

View File

@@ -15,9 +15,12 @@
"vite": "^5.4.21"
},
"dependencies": {
"@vueuse/core": "^14.0.0",
"naive-ui": "^2.43.2",
"pinia": "^3.0.4",
"pixi-viewport": "^6.0.3",
"pixi.js": "^8.14.2",
"vfonts": "^0.0.3"
"vfonts": "^0.0.3",
"vue3-pixi": "^1.0.0-beta.3"
}
}

View File

@@ -1,9 +1,16 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { onMounted, ref, computed } from 'vue'
import { useGameStore } from './stores/game'
import { NCard, NStatistic, NGrid, NGridItem } from 'naive-ui'
import { NConfigProvider, darkTheme, NSelect } from 'naive-ui'
import GameCanvas from './components/game/GameCanvas.vue'
const store = useGameStore()
const filterValue = ref('all')
const filterOptions = computed(() => [
{ label: '所有人', value: 'all' },
...store.avatarList.map(a => ({ label: a.name, value: a.id }))
])
onMounted(async () => {
await store.fetchInitialState()
@@ -12,77 +19,162 @@ onMounted(async () => {
</script>
<template>
<div class="container">
<header>
<h1>修仙世界模拟器 (Web版)</h1>
<div class="status">
<span :class="{ connected: store.isConnected }">
{{ store.isConnected ? '已连接' : '断开连接' }}
</span>
</div>
</header>
<n-config-provider :theme="darkTheme">
<div class="app-layout">
<!-- 顶部状态栏 -->
<header class="top-bar">
<div class="left">
<span class="title">修仙模拟器</span>
<span class="status-dot" :class="{ connected: store.isConnected }"></span>
</div>
<div class="center">
<span class="time">{{ store.year }} {{ store.month }}</span>
</div>
<div class="right">
<span>修士: {{ store.avatarList.length }}</span>
</div>
</header>
<main>
<n-grid :cols="4" :x-gap="12">
<n-grid-item>
<n-card>
<n-statistic label="年份" :value="store.year" />
</n-card>
</n-grid-item>
<n-grid-item>
<n-card>
<n-statistic label="月份" :value="store.month" />
</n-card>
</n-grid-item>
<n-grid-item>
<n-card>
<n-statistic label="当前活跃角色" :value="store.avatarList.length" />
</n-card>
</n-grid-item>
</n-grid>
<div class="main-content">
<!-- 地图区域 (占据主要空间) -->
<div class="map-container">
<GameCanvas />
</div>
<div class="debug-avatars">
<h3>角色列表 (Debug)</h3>
<ul>
<li v-for="av in store.avatarList.slice(0, 10)" :key="av.id">
{{ av.name || 'Unknown' }} [{{ av.x }}, {{ av.y }}] - {{ av.action }}
</li>
</ul>
<!-- 右侧侧边栏 (固定宽度) -->
<aside class="sidebar">
<div class="sidebar-section">
<div class="sidebar-header">
<h3>事件记录</h3>
<n-select
v-model:value="filterValue"
:options="filterOptions"
size="tiny"
class="event-filter"
/>
</div>
<div v-if="store.events.length === 0" class="empty">暂无事件</div>
<div v-else class="event-list">
<div v-for="(event, index) in store.events" :key="index" class="event-item">
{{ event }}
</div>
</div>
</div>
</aside>
</div>
</main>
</div>
</div>
</n-config-provider>
</template>
<style scoped>
.container {
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
header {
.app-layout {
display: flex;
flex-direction: column;
width: 100vw;
height: 100vh;
background: #000;
color: #eee;
overflow: hidden;
}
.top-bar {
height: 36px;
background: #1f1f1f;
border-bottom: 1px solid #333;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
justify-content: space-between;
padding: 0 16px;
font-size: 14px;
z-index: 10;
}
.status span {
padding: 4px 8px;
.top-bar .title {
font-weight: bold;
margin-right: 8px;
}
.status-dot {
display: inline-block;
width: 6px;
height: 6px;
border-radius: 50%;
background: #ff4d4f;
color: white;
border-radius: 4px;
}
.status span.connected {
.status-dot.connected {
background: #52c41a;
}
.debug-avatars {
margin-top: 20px;
background: #f5f5f5;
padding: 10px;
border-radius: 8px;
.main-content {
flex: 1;
display: flex;
position: relative;
overflow: hidden;
}
.map-container {
flex: 1;
position: relative;
background: #111;
overflow: hidden;
}
.sidebar {
width: 400px; /* Increased width */
background: #181818;
border-left: 1px solid #333;
display: flex;
flex-direction: column;
z-index: 20;
}
.sidebar-section {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px;
background: #222;
border-bottom: 1px solid #333;
}
.sidebar-header h3 {
margin: 0;
font-size: 13px;
white-space: nowrap;
}
.event-filter {
width: 200px;
}
.event-list {
flex: 1;
overflow-y: auto;
padding: 8px 12px;
}
.event-item {
font-size: 12px;
color: #ccc;
padding: 4px 0;
border-bottom: 1px solid #333;
}
.event-item:last-child {
border-bottom: none;
}
.empty {
padding: 20px;
text-align: center;
color: #666;
font-size: 12px;
}
</style>

View File

@@ -0,0 +1,74 @@
<script setup lang="ts">
import { useGameStore } from '../../stores/game'
import { useTextures } from './composables/useTextures'
import { computed } from 'vue'
import { Graphics } from 'pixi.js'
const store = useGameStore()
const { textures } = useTextures()
const TILE_SIZE = 64
function getTexture(avatar: any) {
const key = `${(avatar.gender || 'male').toLowerCase()}_${avatar.pic_id || 1}`
return textures.value[key]
}
function getScale(avatar: any) {
const tex = getTexture(avatar)
if (!tex) return 1
return (TILE_SIZE * 1.8) / Math.max(tex.width, tex.height)
}
// Fallback graphics draw function
const drawFallback = (g: Graphics, avatar: any) => {
g.clear()
g.circle(0, 0, TILE_SIZE * 0.6)
g.fill({ color: avatar.gender === 'female' ? 0xffaaaa : 0xaaaaff })
g.stroke({ width: 2, color: 0x000000 })
}
const nameStyle = {
fontFamily: '"Microsoft YaHei", sans-serif',
fontSize: 24,
fill: 0xffffff,
stroke: { color: 0x000000, width: 4 },
align: 'center'
}
</script>
<template>
<container sortable-children>
<container
v-for="avatar in store.avatarList"
:key="avatar.id"
:x="avatar.x * TILE_SIZE + TILE_SIZE / 2"
:y="avatar.y * TILE_SIZE + TILE_SIZE / 2"
:z-index="avatar.y"
>
<!-- Avatar Sprite -->
<sprite
v-if="getTexture(avatar)"
:texture="getTexture(avatar)"
:anchor-x="0.5"
:anchor-y="0.8"
:scale="getScale(avatar)"
/>
<!-- Fallback Graphics -->
<graphics
v-else
@render="g => drawFallback(g, avatar)"
/>
<!-- Name Tag -->
<text
:text="avatar.name"
:style="nameStyle"
:anchor-x="0.5"
:anchor-y="1"
:y="-TILE_SIZE * 0.8"
/>
</container>
</container>
</template>

View File

@@ -0,0 +1,63 @@
<script setup lang="ts">
import { Application } from 'vue3-pixi'
import { ref, onMounted } from 'vue'
import { useElementSize } from '@vueuse/core'
import Viewport from './Viewport.vue'
import MapLayer from './MapLayer.vue'
import EntityLayer from './EntityLayer.vue'
import { useTextures } from './composables/useTextures'
const container = ref<HTMLElement>()
const { width, height } = useElementSize(container)
const { loadTextures, isLoaded } = useTextures()
const mapSize = ref({ width: 2000, height: 2000 })
function onMapLoaded(size: { width: number, height: number }) {
mapSize.value = size
}
const devicePixelRatio = window.devicePixelRatio || 1
onMounted(() => {
loadTextures()
})
</script>
<template>
<div ref="container" class="game-canvas-container">
<!--
antialias: false (像素风必须关闭)
resolution: devicePixelRatio (保证清晰度)
background-color: 0x000000
-->
<Application
v-if="width > 0 && height > 0"
:width="width"
:height="height"
:background-color="0x000000"
:antialias="false"
:resolution="devicePixelRatio"
>
<Viewport
v-if="isLoaded"
:screen-width="width"
:screen-height="height"
:world-width="mapSize.width"
:world-height="mapSize.height"
>
<MapLayer @mapLoaded="onMapLoaded" />
<EntityLayer />
</Viewport>
</Application>
</div>
</template>
<style scoped>
.game-canvas-container {
width: 100%;
height: 100%;
overflow: hidden;
background: #000;
}
</style>

View File

@@ -0,0 +1,103 @@
<script setup lang="ts">
import { ref, onMounted, watch, inject } from 'vue'
import { Container, Sprite } from 'pixi.js'
import { useTextures } from './composables/useTextures'
const mapContainer = ref<Container>()
const { textures, isLoaded } = useTextures()
const TILE_SIZE = 64
const regions = ref<any[]>([])
const emit = defineEmits(['mapLoaded'])
async function initMap() {
if (!mapContainer.value || !isLoaded.value) return
try {
const res = await fetch('/api/map')
const data = await res.json()
const mapData = data.data
regions.value = data.regions || []
if (!mapData) return
// Imperative Tile Rendering
mapContainer.value.removeChildren()
const rows = mapData.length
const cols = mapData[0].length
console.log(`Rendering Map: ${cols}x${rows}`)
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const type = mapData[y][x]
const tex = textures.value[type] || textures.value['PLAIN']
if (tex) {
const s = new Sprite(tex)
s.x = x * TILE_SIZE
s.y = y * TILE_SIZE
s.width = TILE_SIZE
s.height = TILE_SIZE
// Optimization: Static tiles don't need interactivity
s.eventMode = 'none'
mapContainer.value.addChild(s)
}
}
}
// Emit world size
emit('mapLoaded', {
width: cols * TILE_SIZE,
height: rows * TILE_SIZE
})
} catch (e) {
console.error("Map load error", e)
}
}
watch(isLoaded, (val) => {
if (val) initMap()
})
onMounted(() => {
if (isLoaded.value) initMap()
})
function getRegionStyle(type: string) {
const base = {
fontFamily: '"Microsoft YaHei", sans-serif',
fontSize: type === 'sect' ? 48 : 64,
fill: type === 'sect' ? 0xffcc00 : (type === 'city' ? 0xccffcc : 0xffffff),
stroke: { color: 0x000000, width: 8, join: 'round' },
align: 'center',
dropShadow: {
color: '#000000',
blur: 4,
angle: Math.PI / 6,
distance: 4,
alpha: 0.8
}
}
return base
}
</script>
<template>
<container ref="mapContainer">
<!-- Regions (Labels) -->
<text
v-for="r in regions"
:key="r.name"
:text="r.name"
:x="r.x * TILE_SIZE + TILE_SIZE / 2"
:y="r.y * TILE_SIZE + TILE_SIZE / 2"
:anchor="0.5"
:style="getRegionStyle(r.type)"
:z-index="100"
/>
</container>
</template>

View File

@@ -0,0 +1,90 @@
<script setup lang="ts">
import { Viewport as PixiViewport } from 'pixi-viewport'
import { useApplication } from 'vue3-pixi'
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { Container } from 'pixi.js'
const props = defineProps<{
screenWidth: number
screenHeight: number
worldWidth: number
worldHeight: number
}>()
const app = useApplication()
const containerRef = ref<Container>()
let viewport: PixiViewport | null = null
onMounted(async () => {
await nextTick()
if (!containerRef.value || !app.value) return
viewport = new PixiViewport({
screenWidth: props.screenWidth,
screenHeight: props.screenHeight,
worldWidth: props.worldWidth,
worldHeight: props.worldHeight,
events: app.value.renderer.events
})
viewport
.drag()
.pinch()
.wheel()
.decelerate({ friction: 0.9 })
// Initial Fit
fitMap()
const container = containerRef.value
if (container.parent) container.parent.removeChild(container)
app.value.stage.addChild(viewport)
viewport.addChild(container)
;(window as any).__viewport = viewport
})
function fitMap() {
if (!viewport) return
const { worldWidth, worldHeight } = props
// Don't fit if world is default small
if (worldWidth < 100) return
viewport.resize(props.screenWidth, props.screenHeight, worldWidth, worldHeight)
viewport.fit(true, worldWidth, worldHeight)
const fitScale = Math.min(props.screenWidth / worldWidth, props.screenHeight / worldHeight)
// Allow zooming out a bit more than fit
viewport.clampZoom({ minScale: fitScale * 0.8, maxScale: 4.0 })
// If current zoom is weird, reset
if (viewport.scaled < fitScale) viewport.setZoom(fitScale)
}
watch(() => [props.screenWidth, props.screenHeight], ([w, h]) => {
if (viewport) {
viewport.resize(w, h, props.worldWidth, props.worldHeight)
// Optional: Refit on significant resize or just clamp?
// clampZoom updates automatically if minScale is not dynamic?
// No, we set minScale manually. We should re-clamp.
const fitScale = Math.min(w / props.worldWidth, h / props.worldHeight)
viewport.clampZoom({ minScale: fitScale * 0.8, maxScale: 4.0 })
}
})
watch(() => [props.worldWidth, props.worldHeight], () => {
fitMap()
})
onUnmounted(() => {
if (viewport) {
viewport.destroy({ children: false })
}
})
</script>
<template>
<container ref="containerRef">
<slot />
</container>
</template>

View File

@@ -0,0 +1,64 @@
import { ref } from 'vue'
import { Assets, Texture } from 'pixi.js'
// 全局纹理缓存,避免重复加载
const textures = ref<Record<string, Texture>>({})
const isLoaded = ref(false)
export function useTextures() {
const loadTextures = async () => {
if (isLoaded.value) return
const manifest: Record<string, string> = {
'PLAIN': '/assets/tiles/plain.png',
'WATER': '/assets/tiles/water.png',
'SEA': '/assets/tiles/sea.png',
'MOUNTAIN': '/assets/tiles/mountain.png',
'FOREST': '/assets/tiles/forest.png',
'CITY': '/assets/tiles/city.png',
'DESERT': '/assets/tiles/desert.png',
'RAINFOREST': '/assets/tiles/rainforest.png',
'GLACIER': '/assets/tiles/glacier.png',
'SNOW_MOUNTAIN': '/assets/tiles/snow_mountain.png',
'VOLCANO': '/assets/tiles/volcano.png',
'GRASSLAND': '/assets/tiles/grassland.png',
'SWAMP': '/assets/tiles/swamp.png',
'CAVE': '/assets/tiles/cave.png',
'RUINS': '/assets/tiles/ruins.png',
'FARM': '/assets/tiles/farm.png'
}
// 加载地图纹理
for (const [key, url] of Object.entries(manifest)) {
try {
textures.value[key] = await Assets.load(url)
} catch (e) {
console.error(`Failed to load texture: ${url}`, e)
}
}
// 加载角色立绘 (1-16)
for (let i = 1; i <= 16; i++) {
const maleUrl = `/assets/males/${i}.png`
const femaleUrl = `/assets/females/${i}.png`
try {
textures.value[`male_${i}`] = await Assets.load(maleUrl)
} catch (e) { /* ignore */ }
try {
textures.value[`female_${i}`] = await Assets.load(femaleUrl)
} catch (e) { /* ignore */ }
}
isLoaded.value = true
console.log('Textures loaded')
}
return {
textures,
isLoaded,
loadTextures
}
}

View File

@@ -1,9 +0,0 @@
export function setupCounter(element: HTMLButtonElement) {
let counter = 0
const setCounter = (count: number) => {
counter = count
element.innerHTML = `count is ${counter}`
}
element.addEventListener('click', () => setCounter(counter + 1))
setCounter(0)
}

View File

@@ -14,6 +14,7 @@ export const useGameStore = defineStore('game', () => {
const year = ref(0)
const month = ref(0)
const avatars = ref<Record<string, Avatar>>({})
const events = ref<string[]>([]) // 添加事件列表状态
// 计算属性:转换为数组以便遍历
const avatarList = computed(() => Object.values(avatars.value))
@@ -36,6 +37,12 @@ export const useGameStore = defineStore('game', () => {
year.value = data.year
month.value = data.month
// 更新事件日志
if (data.events && Array.isArray(data.events)) {
// 将新事件追加到开头
events.value = [...data.events, ...events.value].slice(0, 100) // 只保留最近100条
}
// 更新 Avatars增量更新逻辑这里后端暂发的是全量/部分列表,直接覆盖位置)
if (data.avatars && Array.isArray(data.avatars)) {
data.avatars.forEach((av: Avatar) => {
@@ -87,6 +94,7 @@ export const useGameStore = defineStore('game', () => {
month,
avatars,
avatarList,
events, // 导出 events
connect,
fetchInitialState
}

View File

@@ -1,96 +1,44 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-family: "HarmonyOS Sans", "PingFang SC", "Microsoft YaHei", system-ui,
-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
line-height: 1.4;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
color: #f6f6f6;
background-color: #050608;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
*,
*::before,
*::after {
box-sizing: border-box;
}
a:hover {
color: #535bf2;
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: #050608;
color: #f6f6f6;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
overflow: hidden;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vanilla:hover {
filter: drop-shadow(0 0 2em #3178c6aa);
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
a {
color: inherit;
text-decoration: none;
}

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="32" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path fill="#007ACC" d="M0 128v128h256V0H0z"></path><path fill="#FFF" d="m56.612 128.85l-.081 10.483h33.32v94.68h23.568v-94.68h33.321v-10.28c0-5.69-.122-10.444-.284-10.566c-.122-.162-20.4-.244-44.983-.203l-44.74.122l-.121 10.443Zm149.955-10.742c6.501 1.625 11.459 4.51 16.01 9.224c2.357 2.52 5.851 7.111 6.136 8.208c.08.325-11.053 7.802-17.798 11.988c-.244.162-1.22-.894-2.317-2.52c-3.291-4.795-6.745-6.867-12.028-7.233c-7.76-.528-12.759 3.535-12.718 10.321c0 1.992.284 3.17 1.097 4.795c1.707 3.536 4.876 5.649 14.832 9.956c18.326 7.883 26.168 13.084 31.045 20.48c5.445 8.249 6.664 21.415 2.966 31.208c-4.063 10.646-14.14 17.879-28.323 20.276c-4.388.772-14.79.65-19.504-.203c-10.28-1.828-20.033-6.908-26.047-13.572c-2.357-2.6-6.949-9.387-6.664-9.874c.122-.163 1.178-.813 2.356-1.504c1.138-.65 5.446-3.129 9.509-5.485l7.355-4.267l1.544 2.276c2.154 3.29 6.867 7.801 9.712 9.305c8.167 4.307 19.383 3.698 24.909-1.26c2.357-2.153 3.332-4.388 3.332-7.68c0-2.966-.366-4.266-1.91-6.501c-1.99-2.845-6.054-5.242-17.595-10.24c-13.206-5.69-18.895-9.224-24.096-14.832c-3.007-3.25-5.852-8.452-7.03-12.8c-.975-3.617-1.22-12.678-.447-16.335c2.723-12.76 12.353-21.659 26.25-24.3c4.51-.853 14.994-.528 19.424.569Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -1,9 +1,16 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { compilerOptions } from 'vue3-pixi'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
plugins: [
vue({
template: {
compilerOptions,
},
}),
],
server: {
proxy: {
'/api': {
@@ -14,8 +21,11 @@ export default defineConfig({
target: 'ws://localhost:8002',
ws: true,
changeOrigin: true,
},
'/assets': {
target: 'http://localhost:8002',
changeOrigin: true,
}
}
}
})