5 Commits

6 changed files with 169 additions and 62 deletions

View File

@ -7,7 +7,7 @@
[![Static Badge](https://img.shields.io/badge/Vite-%23646CFF?style=flat-square&logo=vite&logoColor=white)](https://cn.vite.dev/) [![Static Badge](https://img.shields.io/badge/Vite-%23646CFF?style=flat-square&logo=vite&logoColor=white)](https://cn.vite.dev/)
[![Static Badge](https://img.shields.io/badge/Electron-%2347848F?style=flat-square&logo=electron&logoColor=white)](https://www.electronjs.org/zh/) [![Static Badge](https://img.shields.io/badge/Electron-%2347848F?style=flat-square&logo=electron&logoColor=white)](https://www.electronjs.org/zh/)
一只非常非常可爱的说的道理桌宠(可鬼叫)。 一只非常非常可爱的**说的道理**桌宠(可鬼叫)。
仅供娱乐。 仅供娱乐。
@ -29,6 +29,10 @@ git clone https://github.com/Kisechan/Shuodedaoli-Deskpet.git
```bash ```bash
npm install npm install
cd renderer
npm install
# 本项目的主进程和渲染进程是分离的,需要分别下载环境
``` ```
3. **运行项目** 3. **运行项目**
@ -47,6 +51,6 @@ npm run start
## TODO ## TODO
- [ ] 更美观的说的道理,优化 UI - [x] 更美观的说的道理,优化 UI
- [ ] 更多的哇袄 - [ ] 更多的哇袄
- [ ] 自定义更换不同的道理 - [ ] 自定义更换不同的道理

BIN
build/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -1,6 +1,9 @@
const { app, BrowserWindow, ipcMain } = require("electron"); const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path"); const path = require("path");
const { spawn } = require('child_process') const { spawn } = require('child_process')
const fs = require("fs");
app.disableHardwareAcceleration(); // 高 DPI 缩放修复
// 音效播放器 // 音效播放器
function playAudioFile(filePath) { function playAudioFile(filePath) {
@ -52,15 +55,33 @@ ipcMain.handle('get-sound-path', (_, soundFile) => {
} }
}); });
ipcMain.handle('get-sound-files', async () => {
const soundDir = process.env.NODE_ENV === 'development'
? path.join(__dirname, '../renderer/public/assets/sounds')
: path.join(__dirname, '../renderer/dist/assets/sounds');
try {
// 读取目录下的所有文件名
const files = await fs.promises.readdir(soundDir);
// 筛选出 .mp3 文件并返回
return files.filter(file => file.endsWith('.mp3'));
} catch (error) {
console.error('无法读取声音目录:', error);
return []; // 如果出错则返回空数组
}
});
let mainWindow; let mainWindow;
function createWindow() { function createWindow() {
mainWindow = new BrowserWindow({ mainWindow = new BrowserWindow({
width: 300, width: 200,
height: 300, height: 200,
transparent: true, // 开启透明窗口 transparent: true, // 开启透明窗口
frame: false, // 无边框窗口 frame: false, // 无边框窗口
resizable: false, // 禁止调整大小 resizable: false, // 禁止调整大小
title: "说的道理桌宠",
icon: path.join(__dirname, '../build/icon.png'),
webPreferences: { webPreferences: {
preload: path.join(__dirname, "preload.js"), preload: path.join(__dirname, "preload.js"),
contextIsolation: true, contextIsolation: true,
@ -68,6 +89,21 @@ function createWindow() {
}, },
}); });
// 当渲染进程传来这个事件时,就移动窗口
ipcMain.on('move-window', (event, { x, y }) => {
// 使用 Math.round 避免非整数坐标可能带来的问题
mainWindow.setPosition(Math.round(x), Math.round(y), false);
});
// 添加一个 handle用于响应前端获取窗口位置的请求
ipcMain.handle('get-window-position', () => {
if (mainWindow) {
const [x, y] = mainWindow.getPosition();
return { x, y };
}
return { x: 0, y: 0 };
});
if (process.env.NODE_ENV === "development") { if (process.env.NODE_ENV === "development") {
mainWindow.loadURL("http://localhost:5173"); mainWindow.loadURL("http://localhost:5173");
} else { } else {

View File

@ -9,8 +9,12 @@ contextBridge.exposeInMainWorld('electronAPI', {
} }
}, },
getSoundPath: (soundFile) => ipcRenderer.invoke('get-sound-path', soundFile), getSoundPath: (soundFile) => ipcRenderer.invoke('get-sound-path', soundFile),
getSoundFiles: () => ipcRenderer.invoke('get-sound-files'),
showTooltip: (text) => ipcRenderer.send('show-tooltip', text), showTooltip: (text) => ipcRenderer.send('show-tooltip', text),
onUpdatePosition: (callback) => { onUpdatePosition: (callback) => {
ipcRenderer.on('update-position', (_, position) => callback(position)) ipcRenderer.on('update-position', (_, position) => callback(position))
} },
moveWindow: (position) => ipcRenderer.send('move-window', position),
// 暴露获取窗口位置的函数
getWindowPosition: () => ipcRenderer.invoke('get-window-position')
}) })

View File

@ -1,6 +1,6 @@
{ {
"name": "shuodedaoli-deskpet", "name": "shuodedaoli-deskpet",
"version": "0.1.0", "version": "0.2.0",
"description": "A cute desktop pet of 'Shuodedaoli' built with Electron and Vue 3.", "description": "A cute desktop pet of 'Shuodedaoli' built with Electron and Vue 3.",
"main": "main/main.js", "main": "main/main.js",
"scripts": { "scripts": {
@ -15,15 +15,32 @@
"build": { "build": {
"appId": "com.kisechan.deskpet", "appId": "com.kisechan.deskpet",
"productName": "说的道理桌面宠物", "productName": "说的道理桌面宠物",
"compression": "maximum",
"copyright": "Copyright © 2025 Kisechan", "copyright": "Copyright © 2025 Kisechan",
"directories": { "directories": {
"output": "out" "output": "out"
}, },
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"perMachine": false,
"allowElevation": false,
"installerIcon": "build/icon.ico",
"uninstallerIcon": "build/icon.ico",
"installerHeaderIcon": "build/icon.ico",
"installerLanguages": ["zh_CN", "en_US"],
"language": "2052"
},
"files": [ "files": [
"main/", "main/",
"renderer/dist/", "renderer/dist/",
"package.json" "package.json"
], ],
"publish": {
"provider": "github",
"owner": "Kisechan",
"repo": "Shuodedaoli-Deskpet"
},
"win": { "win": {
"target": "nsis", "target": "nsis",
"icon": "build/icon.png" "icon": "build/icon.png"

View File

@ -1,98 +1,147 @@
<script setup> <script setup>
import { ref } from "vue"; import { ref, onMounted, reactive } from "vue";
import petGif from "./assets/pet.gif"; import petGif from "./assets/pet.gif";
import { Howl } from "howler"; import { Howl } from "howler";
// 配置数据
const tooltips = [
"说的道理~",
"尊尼获加",
"为什么不开大!!",
"(凤鸣)",
];
const soundFiles = [
"cnmb.mp3",
"冲刺,冲.mp3",
"哎你怎么死了.mp3",
"哎,猪逼.mp3",
"啊啊啊我草你妈呀.mp3",
"嘟嘟嘟.mp3",
"韭菜盒子.mp3",
"哇袄.mp3",
];
// 状态管理 // 状态管理
const soundFiles = ref([]); // 存储从主进程获取的声音文件名列表
const showTooltip = ref(false); const showTooltip = ref(false);
const currentTooltip = ref(""); const currentTooltip = ref("");
const isLoading = ref(true); // 跟踪文件列表是否已加载
// 点击事件处理 // 在组件挂载后,从主进程获取声音文件列表
const handleClick = async () => { onMounted(async () => {
const randomSoundFile = if (window.electronAPI && typeof window.electronAPI.getSoundFiles === 'function') {
soundFiles[Math.floor(Math.random() * soundFiles.length)];
console.log("请求播放:", randomSoundFile);
try { try {
const audioUrl = await window.electronAPI?.getSoundPath(randomSoundFile); soundFiles.value = await window.electronAPI.getSoundFiles();
} catch (error) {
if (audioUrl) { console.error("获取声音文件列表失败:", error);
const sound = new Howl({ } finally {
src: [audioUrl], isLoading.value = false;
format: ["mp3"],
});
sound.play();
} else {
console.error("无法获取音频路径:", randomSoundFile);
} }
}
});
const playRandomSound = async () => {
if (isLoading.value || soundFiles.value.length === 0) return;
const randomSoundFile = soundFiles.value[Math.floor(Math.random() * soundFiles.value.length)];
try {
const audioUrl = await window.electronAPI.getSoundPath(randomSoundFile);
if (audioUrl) new Howl({ src: [audioUrl], format: ["mp3"] }).play();
} catch (err) { } catch (err) {
console.error("播放失败:", err); console.error("播放失败:", err);
} }
currentTooltip.value = randomSoundFile.replace(/\.mp3$/, '');
currentTooltip.value = tooltips[Math.floor(Math.random() * tooltips.length)];
showTooltip.value = true; showTooltip.value = true;
setTimeout(() => (showTooltip.value = false), 2000); setTimeout(() => (showTooltip.value = false), 2000);
}; };
const dragState = reactive({
isDragging: false,
hasMoved: false,
// 分别记录鼠标和窗口的起始位置
mouseStartX: 0,
mouseStartY: 0,
windowStartX: 0,
windowStartY: 0,
});
// 鼠标按下事件 (改为异步函数)
async function handleMouseDown(event) {
// 在拖动开始时,先获取窗口的当前位置
const { x, y } = await window.electronAPI.getWindowPosition();
dragState.windowStartX = x;
dragState.windowStartY = y;
// 记录鼠标的初始位置
dragState.mouseStartX = event.screenX;
dragState.mouseStartY = event.screenY;
dragState.isDragging = true;
dragState.hasMoved = false;
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
}
// 鼠标移动事件
function handleMouseMove(event) {
if (!dragState.isDragging) return;
// 计算鼠标从起点移动的距离(偏移量)
const deltaX = event.screenX - dragState.mouseStartX;
const deltaY = event.screenY - dragState.mouseStartY;
if (!dragState.hasMoved && (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5)) {
dragState.hasMoved = true;
}
// 计算窗口的新位置 = 窗口初始位置 + 鼠标偏移量
const newWindowX = dragState.windowStartX + deltaX;
const newWindowY = dragState.windowStartY + deltaY;
// 将计算出的正确位置发送给主进程
window.electronAPI.moveWindow({ x: newWindowX, y: newWindowY });
}
// 鼠标抬起事件
function handleMouseUp() {
// 如果鼠标按下后没有真正移动过,就认为这是一次点击
if (dragState.isDragging && !dragState.hasMoved) {
playRandomSound();
}
// 状态重置
dragState.isDragging = false;
// 移除全局监听器(非常重要)
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
}
</script> </script>
<template> <template>
<div class="pet-container"> <div class="pet-container" @mousedown="handleMouseDown">
<transition name="fade"> <transition name="fade">
<div v-if="showTooltip" class="tooltip"> <div v-if="showTooltip" class="tooltip">
{{ currentTooltip }} {{ currentTooltip }}
</div> </div>
</transition> </transition>
<img :src="petGif" class="pet-gif" @click="handleClick" /> <img :src="petGif" class="pet-gif" />
</div> </div>
</template> </template>
<style> <style>
/* 全局样式保持不变 */
html, body, #app { html, body, #app {
background-color: transparent !important; background-color: transparent !important;
margin: 0; margin: 0;
padding: 0; padding: 0;
overflow: hidden; /* 隐藏滚动条 */ overflow: hidden;
} }
</style> </style>
<style scoped> <style scoped>
/* 样式大大简化 */
.pet-container { .pet-container {
width: 300px; width: 200px;
height: 300px; height: 200px;
/* 将整个容器设置为可拖拽区域 */ position: relative;
-webkit-app-region: drag; cursor: pointer;
user-select: none; /* 防止拖动时选中文本 */
} }
.pet-gif { .pet-gif {
width: 100%; width: 100%;
height: 100%; height: 100%;
cursor: pointer; display: block;
user-select: none; /* 图片现在不接收任何鼠标事件,所有事件都由父容器处理 */
/* 设置图片为不可拖拽,以便响应点击事件 */ pointer-events: none;
-webkit-app-region: no-drag;
} }
.tooltip { .tooltip {
position: absolute; position: absolute;
bottom: -40px; bottom: 10px;
left: 50%; left: 50%;
transform: translateX(-50%); transform: translateX(-50%);
background: rgba(0, 0, 0, 0.7); background: rgba(0, 0, 0, 0.7);
@ -101,16 +150,13 @@ html, body, #app {
border-radius: 20px; border-radius: 20px;
font-size: 14px; font-size: 14px;
white-space: nowrap; white-space: nowrap;
/* 确保提示框不会干扰拖拽 */ pointer-events: none; /* 提示框也不响应鼠标 */
-webkit-app-region: no-drag;
} }
.fade-enter-active, .fade-enter-active, .fade-leave-active {
.fade-leave-active {
transition: opacity 0.3s; transition: opacity 0.3s;
} }
.fade-enter-from, .fade-enter-from, .fade-leave-to {
.fade-leave-to {
opacity: 0; opacity: 0;
} }
</style> </style>