自娱自乐,我的博客(二十)——游戏功能

前言:
   丰富博客的娱乐功能,除了播放音视频,可以增加一些有趣味的小游戏功能。

1 新增game页

  在 /source/game 目录下新建 index.md 文件,如果 game 目录不存在则新建,文件内容如下。

1
2
3
4
5
6
---
title: game
date: 2025-05-01 06:51:00
type: game
top_img: https://img.onlycalm.cn/blogimage/res/Cover%20game.jpg
---

  在 _config.butterfly.yml 中配置新增game menu,比如。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
menu:
# Home: / || fas fa-home
# List||fas fa-list:
# Music: /music/ || fas fa-music
# Movie: /movies/ || fas fa-video
主页: / || fab fa-fort-awesome
文章 || fas fa-book-open:
分类: /categories/ || fas fa-box-open
标签: /tags/ || fas fa-bookmark
时间轴: /archives/ || fas fa-hourglass-half
娱乐 || fas fa-icons:
音乐: /music/ || fas fa-headphones
游戏: /game/ || fas fa-gamepad
友链: /link/ || fas fa-user-friends
打赏: /reward/ || fas fa-gift
关于: /about/ || fab fa-canadian-maple-leaf

   fas fa-gamepad 是设置的游戏图表为手柄,更多图标可在 fontawesome 根据自己喜好选择。

2 2048

  推荐github上开源的2048游戏仓库 gabrielecirulli/2048 ,将该仓库clone下来,拷贝到Hexo博客仓库game目录。
  在 /game/index.yml 文件中添加内容跳转到游戏。点击跳转到游戏后若需刷新一次才能正常游玩,是 PJAX 导致的,解决办法见第 4 节。

1
* [2048](/game/2048/index.html "2048")

2048.png

3 pacman

  推荐github上开源的2048游戏仓库 mumuy/pacman ,将该仓库clone下来,拷贝到Hexo博客仓库game目录。
  在 /game/index.yml 文件中添加内容跳转到游戏。点击跳转到游戏后若需刷新一次才能正常游玩,是 PJAX 导致的,解决办法见第 4 节。

1
* [pacman](/game/pacman/index.html "吃豆子")

pacman.png

  这个游戏的html代码中作者加了安全限制脚本,会定时检查ip地址,如果不是作者自己的域名则会自动跳转过去,可以手动修改删去这段代码。

1
2
3
4
5
6
7
8
9
10
11
<script type="text/javascript">
if(location.protocol!='file:'){
setTimeout(function(){
if(!location.hostname.includes('passer-by.com')){
location.href = 'http://passer-by.com/';
}else if( window.top != window.self ) {
window.top.location = self.location.href;
}
},parseInt(3000+15000*Math.random()));
}
</script>
1
2
<script type="text/javascript" src="https://passer-by.com/public/script/projects.js"></script>
<script type="text/javascript" src="https://passer-by.com/public/script/stat.js"></script>

  可以把游戏代码跟博客仓库一起推送管理,删掉游戏仓库下的 .git 目录。

4 踩坑记录

4.1 游戏报 404 NoSuchKey

  如果点击游戏后报如下 404 错误:

1
2
3
4
404 Not Found
Code: NoSuchKey
Message: The specified key does not exist.
Key: game%2F2048%2Findex.html

  这是因为 clone 游戏仓库到 source/game/2048/ 时,目录里带了 .git 文件夹,git 会把它当成子模块(gitlink,mode 160000)记录,只记了一个 commit 哈希,实际游戏文件并没有提交进博客仓库,所以部署后 /game/2048/index.html 文件不存在。

  解决方法是删掉嵌套的 .git,把游戏文件当作普通文件重新提交:

1
2
3
4
5
6
git rm --cached source/game/2048
rm -rf source/game/2048
git clone https://github.com/gabrielecirulli/2048.git source/game/2048
rm -rf source/game/2048/.git # 关键:删掉嵌套的 .git
git add source/game/2048
git commit -m "fix: 修复2048游戏文件未提交导致404"

4.2 点击游戏后要刷新一次才能开始

  Butterfly 主题默认开启了 PJAX,站内链接会用 AJAX 无刷新加载。但游戏页面是通过相对路径(如 ./static/script/game.js)加载脚本和样式的,PJAX 加载时相对路径解析错乱、脚本不执行,所以游戏打不开,需要刷新一次(完整加载)才能正常。

  解决办法是在 _config.butterfly.yml 的 pjax.exclude 中排除游戏页面,让点击游戏链接时走完整跳转而不是 PJAX:

1
2
3
4
5
pjax:
enable: true
exclude:
- /game/2048/index.html
- /game/pacman/index.html