Sample Javascript UDF

From RPTools Wiki
Revision as of 23:59, 24 April 2023 by Taustin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Languages:  English

This is a very simple side-initiative tracker. It supports two teams, lets you mark one groups of tokens as the player team, the other as the opponent team, then set or clear a state on the whole side at once. Additionally, there is a function for teleporting the team to a map, complete with a list box of maps.


let team = []
let opponents = []
let currentTeam = true;
function setTeam() {
	team = []
	for (let token of MapTool.getSelectedTokens()) {
		team.push(token);
	}
}


function setOpponents() {
	opponents = []
	for (let token of MapTool.getSelectedTokens()) {
		opponents.push(token);
	}
}
function actionDone() {
	let tokens = MapTool.getSelectedTokens()
	for (let token of tokens) {
		MTScript.setVariable("tokenID", token.getId())
		MTScript.evalMacro('[r: setState("Ready", 0, tokenID)]')
	}
}


function sideDone() {
	currentTeam = !currentTeam
	let side1;
	let side2;
	if (currentTeam) {
		side1 = team;
		side2 = opponents
	}
	else {
		side1 = opponents;
		side2 = team;
	}
	for (let token of side1) {
		MTScript.setVariable("tokenID", token.getId())
		MTScript.evalMacro('[r: setState("Ready", 0, tokenID)]')
	}
	for (let token of side2) {
		MTScript.setVariable("tokenID", token.getId());
		MTScript.evalMacro('[r: setState("Ready", 1, tokenID)]');
	}
}




MTScript.registerMacro("setTeam", setTeam);
MTScript.registerMacro("setOpponents", setOpponents);
MTScript.registerMacro("sideDone", sideDone);
MTScript.registerMacro("actionDone", actionDone);

And a related library that uses the same team concept, so uses the same namespace.

function sendToMap(tokens) {
	let maps = JSON.parse(MTScript.evalMacro("[r: getAllMapNames('json')]"))
	let listOption = `targetMap|${maps.join()}|Destination|LIST|SELECT=0 VALUE=STRING`
	
	MTScript.setVariable("listOption", listOption)
	MTScript.evalMacro("[r: input(listOption)]")
	for (let token of tokens) {
		MTScript.setVariable("tokenID", token.getId());
		MTScript.evalMacro("[r: moveTokenToMap(tokenID, targetMap)]")
	}
}

function sendTeamToMap() {
	sendToMap(team)
}

function sendSelectedToMap() {
	sendToMap(MapTool.getSelectedTokens())
}

MTScript.registerMacro("sendTeamToMap", sendTeamToMap);
MTScript.registerMacro("sendSelectedToMap", sendSelectedToMap);

These functions are all then available in MTScript via [r: js.<functionName>].