Compare commits

...

8 Commits

8 changed files with 338 additions and 128 deletions

View File

@ -1 +1,56 @@
# Pet
# Shuodedaoli-Deskpet
[![Static Badge](https://img.shields.io/badge/HTML5-%23E34F26?style=flat-square&logo=html5&logoColor=white)](https://www.w3.org/TR/2011/WD-html5-20110405/index.html)
[![Static Badge](https://img.shields.io/badge/CSS-%23663399?style=flat-square&logo=css&logoColor=white)](https://www.w3.org/Style/CSS/Overview.en.html)
[![Static Badge](https://img.shields.io/badge/JavaScript-%23F7DF1E?style=flat-square&logo=javascript&logoColor=white)](https://www.javascript.com/)
[![Static Badge](https://img.shields.io/badge/Vue.js-%234FC08D?style=flat-square&logo=vuedotjs&logoColor=white)](https://vuejs.org/)
[![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/)
一只非常非常可爱的**说的道理**桌宠(可鬼叫)。
仅供娱乐。
## 主要功能
- **非常可爱**,哇这个好可爱鸭。
- **哇袄!**
- **跨平台**(支持 Windows Linux 和 MacOS
## 使用流程
1. **复制项目**
```bash
git clone https://github.com/Kisechan/Shuodedaoli-Deskpet.git
```
2. **安装依赖**(需要 npm
```bash
npm install
cd renderer
npm install
# 本项目的主进程和渲染进程是分离的,需要分别下载环境
```
3. **运行项目**
```bash
npm run start
```
## 贡献和反馈
欢迎提交 [Issue](https://github.com/Kisechan/Shuodedaoli-Deskpet/issues) 或 [PR](https://github.com/Kisechan/Shuodedaoli-Deskpet/pulls)。
## 许可证
[MIT](./LICENSE).
## TODO
- [x] 更美观的说的道理,优化 UI
- [ ] 更多的哇袄
- [ ] 自定义更换不同的道理

BIN
build/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -1,102 +1,156 @@
const { app, BrowserWindow, ipcMain } = require("electron");
const { app, BrowserWindow, ipcMain, Menu } = require("electron");
const path = require("path");
const { spawn } = require('child_process')
const { spawn } = require("child_process");
const fs = require("fs");
app.disableHardwareAcceleration(); // 高 DPI 缩放修复
// 音效播放器
function playAudioFile(filePath) {
if (process.platform === 'win32') {
spawn('cmd', ['/c', `start "" "${filePath}"`])
} else if (process.platform === 'darwin') {
spawn('afplay', [filePath])
if (process.platform === "win32") {
spawn("cmd", ["/c", `start "" "${filePath}"`]);
} else if (process.platform === "darwin") {
spawn("afplay", [filePath]);
} else {
spawn('aplay', [filePath])
spawn("aplay", [filePath]);
}
}
ipcMain.on('play-sound', (_, soundFile) => {
ipcMain.on("play-sound", (_, soundFile) => {
let soundPath;
// 判断是开发环境还是生产环境
if (process.env.NODE_ENV === 'development') {
if (process.env.NODE_ENV === "development") {
// 在开发模式下,直接指向 renderer/public 里的文件
soundPath = path.join(__dirname, '../renderer/public/assets/sounds', soundFile);
soundPath = path.join(
__dirname,
"../renderer/public/assets/sounds",
soundFile
);
} else {
// 在生产模式下Vite 会把 public 里的文件复制到 dist 文件夹
soundPath = path.join(__dirname, '../renderer/dist/assets/sounds', soundFile);
soundPath = path.join(
__dirname,
"../renderer/dist/assets/sounds",
soundFile
);
}
console.log('Main process trying to play sound at path:', soundPath);
console.log("Main process trying to play sound at path:", soundPath);
if (require('fs').existsSync(soundPath)) {
if (require("fs").existsSync(soundPath)) {
playAudioFile(soundPath);
} else {
console.error('Sound file not found:', soundPath);
console.error("Sound file not found:", soundPath);
}
});
ipcMain.handle('get-sound-path', (_, soundFile) => {
ipcMain.handle("get-sound-path", (_, soundFile) => {
let soundPath;
if (process.env.NODE_ENV === 'development') {
soundPath = path.join(__dirname, '../renderer/public/assets/sounds', soundFile);
if (process.env.NODE_ENV === "development") {
soundPath = path.join(
__dirname,
"../renderer/public/assets/sounds",
soundFile
);
} else {
soundPath = path.join(__dirname, '../renderer/dist/assets/sounds', soundFile);
soundPath = path.join(
__dirname,
"../renderer/dist/assets/sounds",
soundFile
);
}
if (require('fs').existsSync(soundPath)) {
if (require("fs").existsSync(soundPath)) {
// 返回一个可供 web 环境使用的 file 协议 URL
return `file://${soundPath}`;
} else {
console.error('Sound file not found:', soundPath);
console.error("Sound file not found:", soundPath);
return null;
}
});
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 []; // 如果出错则返回空数组
}
});
ipcMain.on("show-context-menu", () => {
const template = [
{
label: "置顶显示",
type: "checkbox",
checked: isAlwaysOnTop, // 菜单项的选中状态与变量同步
click: () => {
isAlwaysOnTop = !isAlwaysOnTop; // 点击时切换状态
mainWindow.setAlwaysOnTop(isAlwaysOnTop); // 并应用到窗口
},
},
{ type: "separator" }, // 分隔线
{
label: "退出",
click: () => {
app.quit(); // 点击时退出应用
},
},
];
const menu = Menu.buildFromTemplate(template);
menu.popup({ window: mainWindow }); // 在主窗口上弹出菜单
});
let isAlwaysOnTop = true;
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 300,
height: 300,
transparent: true,
frame: false,
resizable: false, // 固定大小
width: 200,
height: 200,
transparent: true, // 开启透明窗口
frame: false, // 无边框窗口
resizable: false, // 禁止调整大小
title: "说的道理桌宠",
alwaysOnTop: isAlwaysOnTop, // 窗口始终在最上层
icon: path.join(__dirname, "../build/icon.png"),
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
webSecurity: false, // 信任应用,并允许加载本地资源
webSecurity: false,
},
});
// 开发模式加载Vite服务器
// 当渲染进程传来这个事件时,就移动窗口
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") {
mainWindow.loadURL("http://localhost:5173");
} else {
mainWindow.loadFile(path.join(__dirname, "../renderer/dist/index.html"));
}
// 窗口拖拽功能
let isDragging = false;
mainWindow.webContents.on("before-input-event", (_, input) => {
if (input.type === "mouseDown") {
isDragging = true;
mainWindow.webContents.executeJavaScript(`
window.dragOffset = { x: ${input.x}, y: ${input.y} }
`);
} else if (input.type === "mouseUp") {
isDragging = false;
}
});
mainWindow.on("moved", () => {
if (isDragging) {
mainWindow.webContents.executeJavaScript(`
window.electronAPI.updatePosition()
`);
}
const [x, y] = mainWindow.getPosition();
mainWindow.webContents.send("update-position", { x, y });
});
}
app.whenReady().then(createWindow);

View File

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

View File

@ -1,6 +1,6 @@
{
"name": "shuodedaoli-deskpet",
"version": "0.1.0",
"version": "0.2.0",
"description": "A cute desktop pet of 'Shuodedaoli' built with Electron and Vue 3.",
"main": "main/main.js",
"scripts": {
@ -15,15 +15,32 @@
"build": {
"appId": "com.kisechan.deskpet",
"productName": "说的道理桌面宠物",
"compression": "maximum",
"copyright": "Copyright © 2025 Kisechan",
"directories": {
"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": [
"main/",
"renderer/dist/",
"package.json"
],
"publish": {
"provider": "github",
"owner": "Kisechan",
"repo": "Shuodedaoli-Deskpet"
},
"win": {
"target": "nsis",
"icon": "build/icon.png"

View File

@ -2,11 +2,11 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="icon" type="image/svg+xml" href="assets/icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue + TS</title>
<title>说的道理桌宠</title>
</head>
<body>
<body style="background-color: transparent;">
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

View File

@ -1,102 +1,182 @@
<script setup>
import { ref, onMounted } from "vue";
import { ref, onMounted, reactive } from "vue";
import petGif from "./assets/pet.gif";
import { Howl } from 'howler';
// 配置数据
const tooltips = [
"说的道理~",
"尊尼获加",
"为什么不开大!!",
"(凤鸣)",
];
const soundFiles = [
"cnmb.mp3",
"冲刺,冲.mp3",
"哎你怎么死了.mp3",
"哎,猪逼.mp3",
"啊啊啊我草你妈呀.mp3",
"嘟嘟嘟.mp3",
"韭菜盒子.mp3",
"哇袄.mp3"
];
import { Howl } from "howler";
// 状态管理
const soundFiles = ref([]); // 存储从主进程获取的声音文件名列表
const showTooltip = ref(false);
const currentTooltip = ref("");
const position = ref({ x: 0, y: 0 });
const isLoading = ref(true); // 跟踪文件列表是否已加载
const isPlaying = ref(false); // 是否正在播放音效,用作锁
// 点击事件处理
const handleClick = async () => {
const randomSoundFile = soundFiles[Math.floor(Math.random() * soundFiles.length)];
console.log('请求播放:', randomSoundFile);
try {
const audioUrl = await window.electronAPI?.getSoundPath(randomSoundFile);
if (audioUrl) {
const sound = new Howl({
src: [audioUrl],
format: ['mp3']
});
sound.play();
} else {
console.error('无法获取音频路径:', randomSoundFile);
// 在组件挂载后,从主进程获取声音文件列表
onMounted(async () => {
if (window.electronAPI && typeof window.electronAPI.getSoundFiles === 'function') {
try {
soundFiles.value = await window.electronAPI.getSoundFiles();
} catch (error) {
console.error("获取声音文件列表失败:", error);
} finally {
isLoading.value = false;
}
} catch (err) {
console.error('播放失败:', err);
}
currentTooltip.value = tooltips[Math.floor(Math.random() * tooltips.length)];
showTooltip.value = true;
setTimeout(() => (showTooltip.value = false), 2000);
};
// 初始化位置监听
onMounted(() => {
if (window.electronAPI) {
window.electronAPI.onUpdatePosition((pos) => {
position.value = pos;
});
}
});
const playRandomSound = async () => {
if (isPlaying.value) return;
if (isLoading.value || soundFiles.value.length === 0) return;
const randomSoundFile = soundFiles.value[Math.floor(Math.random() * soundFiles.value.length)];
isPlaying.value = true; // 加锁
try {
const audioUrl = await window.electronAPI.getSoundPath(randomSoundFile);
if (audioUrl) {
new Howl({
src: [audioUrl],
format: ["mp3"],
// 当音频播放结束时
onend: function() {
// 隐藏提示框
showTooltip.value = false;
// 解锁,允许下一次点击
isPlaying.value = false;
}
}).play();
} else {
// 如果音频路径获取失败,也要解锁
isPlaying.value = false;
}
} catch (err) {
// 如果播放过程出错,也要解锁
isPlaying.value = false;
console.error("播放失败:", err);
}
if (randomSoundFile === "哇袄.mp3") {
currentTooltip.value = "哇袄!!!";
} else {
currentTooltip.value = randomSoundFile.replace(/\.mp3$/, '');
}
showTooltip.value = true;
};
const dragState = reactive({
isDragging: false,
hasMoved: false,
// 分别记录鼠标和窗口的起始位置
mouseStartX: 0,
mouseStartY: 0,
windowStartX: 0,
windowStartY: 0,
});
// 鼠标按下事件 (改为异步函数)
async function handleMouseDown(event) {
// 如果按下的不是鼠标左键,则不执行任何操作
if (event.button !== 0) {
return;
}
// 在拖动开始时,先获取窗口的当前位置
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);
}
function handleRightClick() {
window.electronAPI.showContextMenu();
}
</script>
<template>
<div
class="pet-container"
:style="{ left: `${position.x}px`, top: `${position.y}px` }"
@mousedown="handleMouseDown"
@contextmenu.prevent="handleRightClick"
>
<img :src="petGif" class="pet-gif" @click="handleClick" draggable="false" />
<transition name="fade">
<div v-if="showTooltip" class="tooltip">
{{ currentTooltip }}
</div>
</transition>
<img :src="petGif" class="pet-gif" />
</div>
</template>
<style>
/* 全局样式保持不变 */
html, body, #app {
background-color: transparent !important;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
<style scoped>
/* 样式大大简化 */
.pet-container {
position: absolute;
width: 300px;
height: 300px;
-webkit-app-region: no-drag;
width: 200px;
height: 200px;
position: relative;
cursor: pointer;
user-select: none; /* 防止拖动时选中文本 */
}
.pet-gif {
width: 100%;
height: 100%;
cursor: pointer;
user-select: none;
-webkit-user-drag: none;
display: block;
/* 图片现在不接收任何鼠标事件,所有事件都由父容器处理 */
pointer-events: none;
}
.tooltip {
position: absolute;
bottom: -40px;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.7);
@ -105,14 +185,13 @@ onMounted(() => {
border-radius: 20px;
font-size: 14px;
white-space: nowrap;
pointer-events: none; /* 提示框也不响应鼠标 */
}
.fade-enter-active,
.fade-leave-active {
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>