2

背景

我写了一个简单的 WebGL 益智游戏,我想让人们设计和分享他们自己的关卡。

我的想法是将关卡数据存储在 URL 的查询字符串中。如果他们想让朋友尝试关卡,这将让人们简单地分享 URL。

将游戏数据存储在查询字符串中的好方法是什么?

我试过的

目前我通过

"penguins.html?data="+encodeURIComponent(JSON.stringify([X,P]));

这首先将数据转换为 JSON:

[[[[3,-1,0,0,0],[4,-1,0,0,0]]],[{"x":20,"y":20,"dx":0,"dy":0,"vy":2.9999999871229686,"vx":0.0002779607689814708,"thetaf":180,"speed":3,"type":0,"state":6,"steps":0,"numfish":0,"d":4,"size":8},{"x":60,"y":60,"dx":20,"dy":100,"vy":97.51615330485151,"vx":-78.06665276994102,"thetaf":0,"speed":3,"type":17,"state":0,"steps":0,"numfish":0,"d":15,"size":89.00000012433019}]]

然后将其转义为:

[[[[3%2C-1%2C0%2C0%2C0]%2C[4%2C-1%2C0%2C0%2C0]]]%2C[{%22x%22%3A20%2C%22y%22%3A20%2C%22dx%22%3A0%2C%22dy%22%3A0%2C%22vy%22%3A2.9999999871229686%2C%22vx%22%3A0.0002779607689814708%2C%22thetaf%22%3A180%2C%22speed%22%3A3%2C%22type%22%3A0%2C%22state%22%3A6%2C%22steps%22%3A0%2C%22numfish%22%3A0%2C%22d%22%3A4%2C%22size%22%3A8}%2C{%22x%22%3A60%2C%22y%22%3A60%2C%22dx%22%3A20%2C%22dy%22%3A100%2C%22vy%22%3A97.51615330485151%2C%22vx%22%3A-78.06665276994102%2C%22thetaf%22%3A0%2C%22speed%22%3A3%2C%22type%22%3A17%2C%22state%22%3A0%2C%22steps%22%3A0%2C%22numfish%22%3A0%2C%22d%22%3A15%2C%22size%22%3A89.00000012433019}]]

当前方法的缺点

这种方法适用于小级别,但对于更大的级别,我得到了错误:

414. That’s an error.

The requested URL /penguins.html... is too large to process.

看来我当前的主机(Google Appengine)对 URL 的长度有限制。

问题

Javascript 中是否有更好的方法来存储我的游戏数据(即会导致 URI 更短)?

4

4 回答 4

3

由于数据由客户端解析和使用,因此您不需要实际将这些数据发送到服务器。因此,不要使用查询字符串,而是使用 url 的哈希部分:

"penguins.html#" + encodeURIComponent(JSON.stringify([X, P]));

注意#. 现在您可以使用以下方法解析日期:

JSON.parse(location.hash.substring(1));
于 2012-09-14T14:06:09.523 回答
3

I've done something similar where I make a POST to GAE with the JSON data and store it in the datastore with a generated key and return a url based on that key for the user to share.

So you make your post of the JSON data. You store that data in an object like:

/* Annotations ommitted */
public class GameInfo {
    public JSONObject gameData;
    public Integer key;
}

The key is an auto generated int. Then you return to the user a url like: http://www.mygameurl.com/games?id=1234 with id corresponding to the generated key. Then you can let the user share that url to get the game data back from the datastore. It shortens the url that the user is sharing and prevents them from messing with the url and breaking the game data.

于 2012-09-14T14:10:24.497 回答
1

您可以将游戏存储在 sql 数据库中,并将 url 指向其在 DB 上的 ID 以加载它。

或者,如果您愿意,但更复杂,将 url 打包成二进制数据并将其显示为 base64,因此只需解包即可加载游戏。

于 2012-09-14T14:05:45.327 回答
1

这取决于您正在开发的游戏类型,但在某些情况下,特别是在确定性益智游戏中,存储导致特定游戏状态的步骤可能比存储整个状态本身更有效。

例如,假设您正在制作国际象棋游戏,您可以通过保存步骤 (e4,e5;f4,exf4;Bc4...) 而不是所有棋子在棋盘中的位置来保存棋盘状态。如果您的初始游戏状态是程序生成的,您还可以将游戏的初始种子保存在 URL 上。

这样,当您的 servlet 接收到具有特定 URL 的请求时,servlet 可以通过重做给定 URL 的所有步骤来重新计算结束状态。

于 2012-09-14T14:44:01.527 回答