javascript - 带饼干的虫子
问题描述
我目前正在用 Javacript 制作 Flappybird 游戏,现在我正在实现一个 cookie 来存储高分。但问题是,cookie 始终未定义且不会更改。
为了不让任何人感到困惑,我应该说我使用了框架 p5.js,它可以帮助我绘制东西。该代码位于我的 gitHub 存储库 ( https://github.com/HaasStefan/challengeRepo/tree/master/FlappyBird )。主要代码在名为 sketch.js 的文件中,但这里有一些片段:
首先,这是我初始化所有内容的地方,还有 cookie:
function setup() {
createCanvas(400, 600);
bird = new Bird();
menu = new Menu();
pipes.push(new Pipe());
alert(navigator.cookieEnabled);
if (typeof (document.cookie == "undefined"))
document.cookie = "highscore=0; expires=Sun, 1 Dec 2030 12:00:00 UTC; path=/";
}
接下来是读取和更改 cookie 的部分:
let str = document.cookie.split(';');
highscore = str[0].split('=')[1];
if (score > highscore) {
highscore = score;
document.cookie = "highscore=" + highscore + "; expires=Sun, 1 Dec 2030 12:00:00 UTC; path=/";
}
我真的希望你能帮助我解决这个问题,因为我不知道这个错误是什么。谢谢!
解决方案
正如评论中已经提到的那样,第一个问题是 if 条件
if (typeof (document.cookie == "undefined"))
必须写成
if (typeof document.cookie != "undefined")
下一个问题是从“highscore”cookie 中读取值。假设还有其他几个cookie,读取其值的方式应该是:
var highscore = ('; '+document.cookie).split('; highscore=').pop().split(";").shift();
上一行的结果是字符串类型,因此您需要在进行任何比较之前将其转换为 int。
highscore = parseInt(highscore)
总结一下:
if (typeof document.cookie != "undefined") {
document.cookie = "highscore=0; expires=Sun, 1 Dec 2030 12:00:00 UTC; path=/";
}
进而
let str = ('; '+document.cookie).split('; highscore=').pop().split(";").shift();
highscore = str ? parseInt(str) : 0;
if (score > highscore) {
highscore = score;
document.cookie = "highscore=" + highscore + "; expires=Sun, 1 Dec 2030 12:00:00 UTC; path=/";
}
推荐阅读
- bash - 如何通过shell脚本无休止地输入
- javascript - 初学者:如何修复 JavaScript 中的“ReferenceError myFunc is not defined”
- android - 如何在移动设备上本地存储解析的数据
- java - Java8中使用isPresent方法的列表过滤器
- perl - 如何使用 perl 检查文件是否已被使用(打开)。如果是这样,请使用 perl 强制关闭它
- javascript - 如何将多个文件图像加载为数据 url 并在之后单独更改它们
- c# - 使用默认参数执行存储过程
- html - css 和图像导入不适用于 Intellij 中的 Spring Boot
- dart - 无法在颤动中显示小吃店
- python - 有没有办法附加到python中的对象?优先队列