Skip to content

Instantly share code, notes, and snippets.

@IntelOrca
Created January 29, 2021 23:43
Show Gist options
  • Save IntelOrca/a9f90c930d8fa2e04877281be5f8481b to your computer and use it in GitHub Desktop.
Save IntelOrca/a9f90c930d8fa2e04877281be5f8481b to your computer and use it in GitHub Desktop.
Example of an async OpenRCT2 plugin
/// <reference path="C:/Users/Ted/Documents/GitHub/openrct2/distribution/openrct2.d.ts" />
function nextTick() {
return new Promise<void>((resolve, reject) => {
try {
const subscription = context.subscribe('interval.tick', () => {
try {
subscription.dispose();
resolve();
} catch (e) {
reject(e);
}
});
} catch (e) {
reject(e);
}
});
}
async function getAverageGrassLength() {
let steps = 0;
let grassLength = 0;
let grassCount = 0;
const size = map.size;
for (let y = 0; y < size.y; y++) {
for (let x = 0; x < size.x; x++) {
const tile = map.getTile(x, y);
const numElements = tile.numElements;
for (let i = 0; i < numElements; i++) {
const el = tile.getElement(i);
switch (el.type) {
case 'surface':
const surfaceEl = el as SurfaceElement;
const obj = context.getObject('terrain_surface', surfaceEl.surfaceStyle);
if (obj && obj.identifier === 'rct2.surface.grass') {
grassLength += surfaceEl.grassLength;
grassCount++;
}
break;
}
}
steps++;
if (steps >= 1000) {
steps = 0;
await nextTick();
}
}
}
if (grassCount == 0) return 0;
return Math.round(grassLength / grassCount);
}
const main = () => {
if (typeof ui === 'undefined') {
console.log("Plugin not available on headless mode.");
return;
}
ui.registerMenuItem('async test', async () => {
const grassLen = await getAverageGrassLength();
park.postMessage('Average grass length: ' + grassLen);
});
};
registerPlugin({
name: 'Async Test',
version: '1.0',
authors: ['OpenRCT2'],
type: 'remote',
licence: 'MIT',
main: main
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment