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

@@ -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