首页 > 解决方案 > 带饼干的虫子

问题描述

我目前正在用 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=/";
}

我真的希望你能帮助我解决这个问题,因为我不知道这个错误是什么。谢谢!

标签: javascriptcookiesp5.js

解决方案


正如评论中已经提到的那样,第一个问题是 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=/";
}

推荐阅读