繁体   English   中英

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

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

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

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

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

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

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

它只是看起来像一个对象,也表现得像一个对象。 但是对于香草对象,您无法执行以下映射字典操作。

const dict = {};

const key1 = { row: 0, col: 1 };
const value1 = { some: 'value' };

dict[key1] = value; // will not work

这就是我想要的,我试图使映射尽可能简单。 使用Immutable.js中的 Record and Map ,您可以执行以下操作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM