Draw the map
Pictures, numbers, boards and every other value that a world shows besides its text reach the view in data. The view now draws the map of Treasure Island, the position of the person and the level of the tide from the data of the world.
The data of the world
world.data is an object that maps each name chosen by the world to a value ready to use. Treasure Island has three names:
map: the island as an array of rows, each an array of cells. A cell is a string (🌊 for water, 🌴 for a palm tree, ⛰️ for a rock and · for sand).position: the cell of the person as{ row, column }.tide: a number from 0 to 100.
Each world chooses its own names and the shape of their values. A real world defines them in its own code and in a fake world you choose them yourself.
Data in a fake world
The data of a fake world maps each name to a fixed value or to a function of time called every second to compute the new value.
data: {
map: MAP,
position: { row: 3, column: 1 },
// The tide rises and falls: a function of time gives a new value every second.
tide: (time) => Math.round(50 + 40 * Math.sin(time / 8000)),
},MAP is the array of rows defined above the fake world. The tide exists only as an example of a changing value. Since the view renders the whole world again on every change, the bar of the tide in the example below moves without any code written for the tide.
Draw a grid
The view iterates over the rows of the map and over the cells of each row. The cell at position shows 🧍 in place of the ground:
map.forEach((row, rowIndex) => {
row.forEach((ground, columnIndex) => {
const isHere = rowIndex === position.row && columnIndex === position.column;
// ...a cell that shows '🧍' when isHere, and the ground otherwise
});
});A CSS grid with gridTemplateColumns: repeat(5, 44px) gives each cell of a row its own column. The 5 is the length of a row (map[0].length).
In React the IslandMap component renders the cells. The plain JavaScript function islandMap creates the grid once and rebuilds its cells on every change of the world. Rebuilding costs little for 25 plain boxes without listeners.
Data can be missing
The value of a name in data stays undefined until the world sends it for the first time. Check the value before drawing and render a placeholder while it is missing:
if (!map || !position) return <p>The map is on its way…</p>;The code
The new lines are highlighted.
import { useWorld } from './useWorld.js';
// A fake world to build with, a small treasure hunt that needs no account and no network.
// The island, row by row: 🌊 water, 🌴 palm trees, ⛰️ rocks, · sand.
const MAP = [
['🌊', '🌊', '🌴', '🌊', '🌊'],
['🌊', '🌴', '·', '⛰️', '🌊'],
['🌴', '·', '·', '·', '🌴'],
['🌊', '·', '⛰️', '·', '🌊'],
['🌊', '🌊', '·', '🌴', '🌊'],
];
const island = {
name: 'Treasure Island',
profile: { description: 'A treasure is buried somewhere on this island. Find it!' },
now: { text: 'The hunt is on.' },
// What the world shows, by name.
data: {
map: MAP,
// Where you are on the map.
position: { row: 3, column: 1 },
// The tide rises and falls: a function of time gives a new value every second.
tide: (time) => Math.round(50 + 40 * Math.sin(time / 8000)),
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: island } });
// The three states of every view: it failed, it is connecting, it is here.
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<main>
<Header world={world} />
<IslandMap data={world.data} />
</main>
);
}
// The name of the world, what it is about and what is happening now.
function Header({ world }) {
return (
<header>
<h1>{world.name}</h1>
<p>{world.profile.description}</p>
<p>
Now: {world.now?.text} The world is {world.status}.
</p>
</header>
);
}
// The island from the data of the world: one square per cell, you on yours, and the tide.
function IslandMap({ data }) {
const { map, position, tide } = data;
// A name of `data` can be missing for a moment while the world sends it.
if (!map || !position) return <p>The map is on its way…</p>;
return (
<section>
<div
role="img"
aria-label="Map of the island"
style={{ display: 'grid', gridTemplateColumns: `repeat(${map[0].length}, 44px)`, gap: 2 }}
>
{map.map((row, rowIndex) =>
row.map((ground, columnIndex) => {
const isHere = rowIndex === position.row && columnIndex === position.column;
return (
<div
key={`${rowIndex}-${columnIndex}`}
style={{
height: 44,
display: 'grid',
placeItems: 'center',
fontSize: 24,
borderRadius: 6,
background: isHere ? 'rgba(255, 190, 0, 0.6)' : 'rgba(127, 127, 127, 0.12)',
}}
>
{isHere ? '🧍' : ground}
</div>
);
}),
)}
</div>
<p>
Tide <meter min={0} max={100} value={tide} /> {tide}%
</p>
</section>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world to build with, a small treasure hunt that needs no account and no network.
// The island, row by row: 🌊 water, 🌴 palm trees, ⛰️ rocks, · sand.
const MAP = [
['🌊', '🌊', '🌴', '🌊', '🌊'],
['🌊', '🌴', '·', '⛰️', '🌊'],
['🌴', '·', '·', '·', '🌴'],
['🌊', '·', '⛰️', '·', '🌊'],
['🌊', '🌊', '·', '🌴', '🌊'],
];
const island = {
name: 'Treasure Island',
profile: { description: 'A treasure is buried somewhere on this island. Find it!' },
now: { text: 'The hunt is on.' },
// What the world shows, by name.
data: {
map: MAP,
// Where you are on the map.
position: { row: 3, column: 1 },
// The tide rises and falls: a function of time gives a new value every second.
tide: (time) => Math.round(50 + 40 * Math.sin(time / 8000)),
},
};
// The page: one element that holds the whole view.
const page = document.createElement('main');
page.textContent = 'Connecting…';
document.body.append(page);
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: island } });
page.textContent = '';
header(page, world);
islandMap(page, world);
// The name of the world, what it is about and what is happening now.
function header(container, world) {
const title = document.createElement('h1');
const about = document.createElement('p');
const now = document.createElement('p');
container.append(title, about, now);
// Called at once, then after every change of the world.
return world.subscribe((node) => {
title.textContent = node.name;
about.textContent = node.profile.description ?? '';
now.textContent = `Now: ${node.now?.text ?? ''} The world is ${node.status}.`;
});
}
// The island from the data of the world: one square per cell, you on yours, and the tide.
function islandMap(container, world) {
const grid = document.createElement('div');
grid.setAttribute('role', 'img');
grid.setAttribute('aria-label', 'Map of the island');
grid.style.cssText = 'display: grid; gap: 2px';
const tide = document.createElement('p');
const meter = document.createElement('meter');
meter.min = 0;
meter.max = 100;
const level = document.createElement('span');
tide.append('Tide ', meter, level);
container.append(grid, tide);
return world.subscribe((node) => {
const { map, position } = node.data;
// A name of `data` can be missing for a moment while the world sends it.
if (!map || !position) {
grid.textContent = 'The map is on its way…';
return;
}
grid.style.gridTemplateColumns = `repeat(${map[0].length}, 44px)`;
const cells = [];
map.forEach((row, rowIndex) => {
row.forEach((ground, columnIndex) => {
const isHere = rowIndex === position.row && columnIndex === position.column;
const cell = document.createElement('div');
cell.style.cssText = 'height: 44px; display: grid; place-items: center; font-size: 24px; border-radius: 6px';
cell.style.background = isHere ? 'rgba(255, 190, 0, 0.6)' : 'rgba(127, 127, 127, 0.12)';
cell.textContent = isHere ? '🧍' : ground;
cells.push(cell);
});
});
grid.replaceChildren(...cells);
meter.value = node.data.tide;
level.textContent = ` ${node.data.tide}%`;
});
}Next steps
The person cannot move yet. On this island a move is a message to the world and the view first needs the conversation that step 3: Talk with the world adds.
The data of the world covers every kind of value a world can send and how to render it. The recipe Draw a grid on a canvas draws a grid like this map on a canvas.