Introduction to inkjs
Inkjs is a powerful JavaScript library used for parsing and playing stories written in the Ink markup language. It allows developers to create rich, interactive narratives for games or web applications that can be easily managed and maintained.
Inkjs API Examples
Loading a Story
const inkjs = require('inkjs');
const storyContent = {"inkVersion":20,"root":[["^Hello, World!","\n","done",["end",null]]]};
const story = new inkjs.Story(storyContent);
Checking for Available Choices
if (story.canContinue) {
console.log(story.Continue());
} else if (story.currentChoices.length > 0) {
story.currentChoices.forEach((choice) => {
console.log(choice.text);
});
}
Handling Choices
const choiceIndex = 0; // Index of the selected choice
story.ChooseChoiceIndex(choiceIndex);
if (story.canContinue) {
console.log(story.Continue());
}
Bookmarks and Save Points
const savedState = story.state.toJson();
story.state.LoadJson(savedState); // Restore saved state
Variables and External Functions
story.variablesState.$("player_score", 10);
const score = story.variablesState.$("player_score");
console.log(score); // Outputs: 10
story.BindExternalFunction("addScore", (score) => {
let playerScore = story.variablesState.$("player_score");
playerScore += score;
story.variablesState.$("player_score", playerScore);
});
story.EvaluateFunction("addScore", [5]);
console.log(story.variablesState.$("player_score")); // Outputs: 15
Tags and Globals
story.tags.forEach((tag) => {
console.log(tag);
});
story.globalTags.forEach((glTag) => {
console.log(glTag);
});
Sample Application Using Inkjs
Below is an example of a simple web application that uses Inkjs to display a story with interactive choices:
<!DOCTYPE html>
<html>
<head>
<title>Interactive Story</title>
<script src="https://cdn.jsdelivr.net/npm/inkjs/dist/ink.js"></script>
</head>
<body>
<div id="storyContainer"></div>
<script>
const storyContent = {"inkVersion":20,"root":[["^Welcome to the story.","\n","choice:Go left","*","\n","left","\n","^You went left.","\n","end","\n","done",null,"choice:Go right","*","\n","right","\n","^You went right.","\n","done",null,"end",null]];
const story = new inkjs.Story(storyContent);
const storyContainer = document.getElementById('storyContainer');
function showStory() {
if (story.canContinue) {
storyContainer.innerHTML += story.Continue() + '<br>';
showChoices();
}
}
function showChoices() {
while (story.currentChoices.length > 0) {
let choice = story.currentChoices.pop();
const choiceButton = document.createElement('button');
choiceButton.textContent = choice.text;
choiceButton.onclick = () => {
story.ChooseChoiceIndex(choice.index);
showStory();
};
storyContainer.appendChild(choiceButton);
}
}
showStory();
</script>
</body>
</html>
This application demonstrates how to load a story, display interactive choices, and handle user selections using Inkjs APIs.
Hash: 66db2c6811de1d83ad53c9cf41890b71e8eec64da89df8a752528b90fc5957c1