Immutable.js:表示2D游戏场的数据结构

Immutable.js: Data structure to represent 2D game field

本文关键字:游戏场 数据结构 2D 表示 js Immutable      更新时间:2024-06-02

我想知道我应该用什么数据结构来表示一个方形游戏板(考虑每个单元格可以有一些颜色)。最自然的想法是二维列表,但很难查询和更改它

因此,现在使用一个Map,其中键是${x}.${y}(JS中没有元组:(),值是表示颜色的字符串类似这样的东西:

Map([['0.0', 'red'], ['0.1', 'red'], ['1.0', 'blue'], ['1.1', 'red']])

使用这样的数据结构可以吗?在Immutable.js方面有更好的解决方案吗?

我也在构建自己的2D游戏板,我也遇到了同样的问题。我做的解决方案是Record

它只是看起来像一个物体,行为也像一个。但是对于vanilla对象,您不能执行以下映射字典的操作。

const dict = {};
const key1 = { row: 0, col: 1 };
const value1 = { some: 'value' };
dict[key1] = value; // will not work

不过,这正是我想要的,我试图使映射尽可能简单地处理。使用Immutable.js中的RecordMap,可以执行以下操作。

import { Map, Record } from 'immutable';
const dict = Map();
const Pos = Record({ row: 0, col: 0 }); // some initial value.
const Val = Record({ some: 'value' }); // same here.
const key1 = new Pos({ row: 0, col: 1 });
const value1 = new Val({ some: 'value' });
dict = dict.set(key1, value1); // works like you wish

你可以阅读官方文档了解更多信息。也许你有更好的解决方案,请告诉我:)。

是否有原因不能使用这样的二维数组:

let square = [
    ['red', 'green', 'blue'],
    ['orange', 'red', 'blue'],
    ['red', 'blue', 'blue']
];

然后,您可以将上述数据结构添加到地图中。

因此,要访问中间的瓦片,只需使用数组的[1][1]索引即可。

我很好奇为什么您认为列表列表很难查询和更改。可以使用长度为2的数组作为[x, y]对,并将其传递给getInsetInupdateIn方法。

let grid = Immutable.toJS([
    ['red', 'green'],
    ['blue', 'yellow']
]);
grid.getIn([0, 1]); // => 'green';
grid = grid.setIn([0, 1], 'purple');
grid.getIn([0, 1]); // => 'purple';
grid = grid.updateIn([0, 0], cell => cell.toUpperCase());
grid.getIn([0, 0]); // => 'RED';

使用map(...):可以很容易地将一些函数应用于网格中的每个单元

grid.map((row, x) => row.map(cell, y) => x + cell + y);
grid.get([1, 1]); // => '1yellow1'

有一件事可能比Map更棘手,那就是试图找到一个值的坐标。

const x = grid.findIndex(row => row.contains('blue')); // => 1
const y = grid.get(x).indexOf('blue'); // => 0
grid.get([x, y]); // => blue