Language Guide
Matt Mower
- Part 1: Getting Started
- Part 2: Core Concepts
- Part 3: Building Interactive Content
- Part 4: Advanced Features
- Part 5: Technical Reference
- Miscellaneous Topics
Part 1: Getting Started
What is Rez?
Rez is a language for creating choice-based HTML games/interactive fiction.
If you have ever wanted to build choice-based games with inventories, smart NPCs, and complex mechanics without fighting your tools, Rez may be for you.
Think of it as a powerful alternative to Twine. While Twine democratized interactive fiction creation and remains excellent for narrative-focused projects, more complex games push the limits and need a tool designed to support that complexity. This is where Rez comes into its own.
Rez uses an easy-to-learn declarative syntax and only requires Javascript for advanced features.
It makes it easy to build:
-
Rich NPCs with memory, behavior trees, and complex interactions
-
Dynamic inventories where a ring works differently on your hand vs in your backpack
-
Flexible layouts that adapt to different game requirements (combat, dialogue, exploration)
-
Procedural content that creates unique experiences on each playthrough
-
New mechanics that we didn’t think of
Rez sits between the simplicity of Twine and the complexity of parser-based systems like Inform while offering many of the benefits of both.
A Simple Example
Here’s a taste of what Rez code looks like:
@card greeting {
visit_count: 0
content: ```
<p>Hello! This is visit number ${card.visit_count}.</p>
<p><a card="greeting">Visit again</a></p>
```
on_start: (card) => {
card.visit_count += 1;
}
}
This creates an interactive card that tracks how many times it’s been visited.
This tiny example demonstrates Rez’s core philosophy: clean separation between what the players see and what happens behind the scenes. Scale this approach up and you can build any choice-based game you can imagine.
Installation and Setup
To get started with Rez, you’ll need to have the Rez compiler installed on your system. Download the latest release for your operating system and install it. The installer will automatically download and install the compiler and its runtime dependencies for your platform.
Once the installer is complete you will have an executable named either rez_macos, rez_linux, or rez_windows.exe depending on your platform. Move or copy that executable into your path. The name of the executable doesn’t matter so you can rename it rez or rc (for rez compiler) as you like.
Once installed, you can create a new game project with:
rez new my_first_game --author-name="Your Name" --author-email="you@example.com" --game-title="My First Game"
This creates a folder called my_first_game with the following structure:
my-first-game/ ├── src/ │ └── my-first-game.rez # Your game source code ├── lib/ │ └── stdlib.rez # Rez standard library (don't modify) ├── assets/ # Images, sounds, etc. └── dist/ # Compiled game files (created on build)
The stdlib.rez file is contains a basic library of elements that Rez games can depend upon. You should not modify this file as it will be regenerated every time the rez compiler is run. When you upgrade to a newer version of Rez it will automatically install the newest standard library. You may put other Rez source files in the lib folder and they will not be interfered with.
Put any asset files you want to distribute with your game into the assets folder.
The dist folder will be recreated each time the Rez compiler runs and will contain a complete, ready to distribute, version of your game including all runtime files and used assets. You can package or upload this folder to share your game.
Once the compiler has run you may add other files or post process files in the dist folder but be aware any such changes may be overwritten the next time the compiler runs. The @pragma directive is designed to allow for extra processing steps in the compilation process. For example a @pragma could be used to convert graphics into different formats or minify files. This will ensure the step happens every time the compiler runs.
Your First Game
Let’s create a simple but complete game to understand the basics. Open src/my-first-game.rez and replace everything from @game onwards with:
@game {
name: "treasure_hunt"
title: "Treasure Hunt"
author_name: "Matt Mower"
author_email: "self@mattmower.com"
game_homepage: "http://mattmower.com/"
IFID: "12345678-1234-5678-9ABC-123456789ABC"
archive_format: 1
version: 1.0
created: "2025-07-20 14:01:27.161254Z"
initial_scene_id: #opening_scene
layout: ```
<section class="main-content is-fullheight">
<section class="hero">
<div class="hero-body">
<p class="title">${game.title}</p>
<p class="sub_title">a game by <a href="${game.game_homepage}">${game.author_name}</a></p>
</div>
</section>
<div class="container">
${content}
</div>
</section>
```
}
@scene opening_scene {
initial_card_id: #forest_entrance
}
@card forest_entrance {
content: ```
<p>You stand at the edge of a dark forest. A weathered sign reads "TREASURE WITHIN".</p>
<p>What do you want to do?</p>
<ul>
<li><a card="enter_forest">Enter the forest</a></li>
<li><a card="examine_sign">Examine the sign more closely</a></li>
</ul>
```
}
@card enter_forest {
content: ```
<p>You push through the undergrowth and find yourself in a small clearing.
In the center sits an old wooden chest!</p>
<p><a card="open_chest">Open the chest</a></p>
<p><a card="forest_entrance">Go back to the entrance</a></p>
```
}
@card examine_sign {
content: ```
<p>Looking closer at the sign, you notice small text at the bottom:
"Beware the guardian of the treasure."</p>
<p><a card="forest_entrance">Return to the entrance</a></p>
```
}
@card open_chest {
bindings: [player: #player]
content: ```
$if(player.has_key) -> {%
<p>Using the key, you open the chest and find a pile of gold coins!
You win!</p>
<p><a card="forest_entrance">Play again</a></p>
%}
() -> {%
<p>The chest is locked tight. You need a key.</p>
<p><a card="search_area">Search the area for a key</a></p>
<p><a card="enter_forest">Go back</a></p>
%}
```
}
@card search_area {
content: ```
<p>You search around the clearing and find a rusty key hidden under some leaves!</p>
<p><a card="open_chest">Try the key on the chest</a></p>
```
on_start: (card) => {
$player.has_key = true;
}
}
@actor player {
$global: true
has_key: false
}
|
Note
|
Notice the A Use |
Compiling and Running the Game
From the my_first_game folder run:
➜ rez compile src/my_first_game.rez rez v1.8.15 — compiled to dist folder
Then open the dist/index.html file. There’s a version online and it should look like:
Distributing Your Game
Package the contents of the dist folder in any way you like.
Understanding the Structure
Let’s break down what we just created:
@game: The top-level container that defines the game’s metadata and overall layout. Every Rez game needs exactly one @game` element and it always has the id #game. It must also have an attribute initial_scene_id that refers to the scene that starts the game.
@scene: A context where interactions take place, can have a layout (for example a dialogue scene might use a different layout to an inventory scene). Each scene has an initial_card_id that defines which @card` gets presented first when that scene starts. You can have one scene or many scenes.
@card: The content that players mostly see and interact with. Cards contain the text, choices, and behaviors that make up your game. It must have a content: attribute containing a template (HTML markup and Rez template expressions) that determines what the player will see.
The structure flows like this:
@game layout
└── @scene layout
└── @card content
Compilation and Testing
To build your game, run:
rez compile src/my-first-game.rez
This creates the compiled game in the dist/ folder. Open dist/index.html in a web browser to play your game.
The compilation process:
-
Reads your
.rezsource files -
Converts them to JavaScript objects
-
Creates an HTML page with embedded JavaScript
-
Copies any assets to the distribution folder
Checking your game without building it
rez lint runs every check the compiler makes but doesn’t write the game files. It’s quicker than a full compile and is useful for checking your work as you go:
rez lint src/my-first-game.rez
It prints any errors and exits with a non-zero status if there are any. Like rez compile it updates lib/stdlib.rez.
Looking up an element’s attributes
rez schema describes the attributes an element accepts: their types, which are required, their default values, and any other rules. With no arguments it lists the elements that have a schema:
rez schema rez schema card
To include the elements, schemas and defaults defined in your own game, give it your game source first:
rez schema src/my-first-game.rez npc
A compact language reference
rez docs prints a short reference to the Rez language. It is written for AI assistants that are helping you write a game, and for authors who want a quick reminder rather than a tutorial. rez docs topics lists the topics and rez docs <topic> prints one of them, for example rez docs templates.
Next Steps
Now that you have a working game, you can:
-
Add more cards and scenes to expand the story
-
Include images and other assets
-
Add dynamic behavior with JavaScript
-
Experiment with different layout modes
In the next section, we’ll dive deeper into the core concepts that make Rez games work.
Part 2: Core Concepts
Understanding Elements
Rez games are built from elements - the building blocks that define everything in your game. Elements represent things like the game itself, scenes, cards, characters, items, and more. Rez has a number of useful elements built in and you can also create your own when you need to.
Every element follows the same basic pattern. It starts with an @ symbol that says "we’re declaring an element", this is followed by the element name (e.g. game), then a matched pair of braces {} inside which are attributes that define that element. So:
@element_name unique_id {
attribute_name: value
another_attribute: another_value
}
For example:
@item magic_sword {
name: "Enchanted Blade"
damage: 15
magic: true
}
The Three Essential Elements
Every Rez game uses three core elements (@game, @scene, and @card) and if you wanted to you could build your entire game with just these three elements.
@game - The overall game container that holds game metadata and the "master" layout.
@game {
name: "adventure"
title: "Sandbags Mythical Adventure"
initial_scene_id: #sc_opening
author: "Matt Mower"
author_email: "self@mattmower.com"
layout: ```
<section class="hero">
<div class="hero-body">
<p class="title">${game.title}</p>
<p class="subtitle">By ${game.author}</p>
</div>
</section>
${content}
```
}
The @game element is the only element where you don’t specify the element id, it always #game and you can’t change it. Every other element you will give an id yourself.
@scene - A context for a kind of player interaction that can have its own layout. You can write your entire game in one scene, or use as many as you like to present content appropriately in that context. For example different scenes might a different number of columns, font choices, colours and so on.
@scene opening {
initial_card_id: #start_here
blocks: [sidebar: #sidebar]
layout: ```
<div class="columns-2">
<div class="column">${sidebar}</div>
<div class="column">${content}</div>
</div>
```
}
@card - Content that players see and interact with, presented within a scene. If you are familiar with Twine then a @card is roughly equivalent to a Twine passage.
@card start_here {
content: ```
<p>Your adventure begins...</p>
<p><a card="next_card">Continue</a></p>
```
}
The layout: attribute of the game and its scenes and the content: attribute of cards are where you put the HTML markup that is shown to the player. Scenes that share a layout can define it once with the @layout directive, see Sharing Layouts with @layout.
Element Unique Identifiers
Every game element must have a unique id by which it can be referenced.
In Rez element ids follow the JavaScript rules for naming identifiers:
-
Start with a letter, underscore, or dollar sign
-
Can contain letters, numbers, underscores, or dollar signs
-
Cannot contain spaces or special characters
-
Are case-sensitive
Good IDs: forest_entrance, magic_sword, npc_wizard, scene1
Bad IDs: forest entrance, magic-sword, 123start, npc@wizard
Understanding Attributes
Attributes are how you describe an element’s properties and behavior. They use the format name: value with a required space after the colon.
@card treasure_room {
title: "The Treasure Chamber" %% String
visited: false %% Boolean
gold_count: 100 %% Number
room_type: :treasure %% Keyword (symbol)
owner_id: #dragon %% Element reference
%% Template (multi-line string)
content: ```
<p>A room filled with gold!</p>
```
%% Event script function
on_enter: (card) => {
card.visited = true;
}
%% Action script function
refill_gold: function() {
this.gold_count = 100;
}
}
|
Note
|
Comments: In Rez source a comment starts with The |
Attribute Types
Strings - Text enclosed in double quotes
description: "A rusty old key"
Numbers - Integers or decimals
damage: 15 weight: 2.5 price: -10
Booleans - True or false values
magic: true cursed: false found: yes %% yes/no also work hidden: no
Keywords - Symbols starting with a colon, useful for categories
material: :gold rarity: :legendary type: :weapon
|
Important
|
All keywords are converted into strings in the Javascript code. However every keyword is
also turned into a constant, for example |
Element References - Point to another element by referencing its id with #
owner_id: #player location_id: #forest wielded_by_id: #hero
|
Important
|
The @scene forest {
initial_card_id: #entrance %% You define this
%% Rez automatically creates:
%% initial_card -> the actual RezCard object
}
@actor hero {
location_id: #forest %% You define this
%% Rez automatically creates:
%% location -> reference to the object with ID #forest
}
This means you can use both |
Templates - Multi-line content with dynamic expressions
content: ```
<p>Welcome, ${player.name}!</p>
<p>You have ${player.gold} gold coins.</p>
```
Lists - Collections of values (space-separated, no commas)
colors: [:red :green :blue] numbers: [1 2 3 4 5] names: ["Alice" "Bob" "Charlie"] items: [#sword #shield #potion]
Event Scripts - JavaScript functions for handling events
on_use: (item) => {
player.health += 10;
return RezEvent.playCard("feeling_better");
}
Event script functions are written as arrow functions and passed the event receiving object as their first parameter.
Action Script - Javascript functions for performing behaviours
use: function() {
this.uses -= 1;
}
Action script functions are written in the standard Javascript function format
and utilise this as a reference to the object whose action script is being
executed.
|
Tip
|
Event Response Methods: Event scripts must use RezEvent to specify what happens as a result of the event:
Methods can be chained: |
Dynamic Properties
Dynamic properties are attributes that calculate their value each time they’re accessed, rather than storing a fixed value. They’re perfect for derived stats, percentages, and values that depend on other attributes.
Basic Dynamic Properties
Use ^p{…} to define a property that recalculates automatically:
@actor hero {
first_name: "Sir"
last_name: "Galahad"
%% This calculates every time it's accessed
full_name: ^p{
return `${this.first_name} ${this.last_name}`;
}
health: 85
max_health: 100
%% Perfect for UI elements like health bars
health_percentage: ^p{
return this.health * 100 / this.max_health;
}
%% Boolean states based on other attributes
is_healthy: ^p{
return this.health > this.max_health * 0.5;
}
is_at_full_health: ^p{
return this.health >= this.max_health;
}
}
Practical Examples
Dynamic properties shine for calculated stats:
@actor character {
strength: 15
dexterity: 12
intelligence: 14
%% Calculated modifier (D&D style)
strength_modifier: ^p{
return Math.floor((this.strength - 10) / 2);
}
dex_modifier: ^p{
return Math.floor((this.dex - 10) / 2);
}
%% Total of all stats
total_stats: ^p{
return this.strength + this.dexterity + this.intelligence;
}
%% Armor class calculation
base_armor: 10
armor_bonus: 2
armor_class: ^p{
return this.base_armor + this.dex_modifier + this.armor_bonus;
}
}
For inventory and resource management:
@actor player {
gold: 150
silver: 75
copper: 200
%% Total wealth in copper pieces
total_wealth: ^p{
return this.copper + (this.silver * 10) + (this.gold * 100);
}
current_weight: 45
max_carrying_capacity: 100
%% How much more can be carried
carrying_capacity_remaining: ^p{
return Math.max(0, this.max_carrying_capacity - this.current_weight);
}
%% Whether player is overloaded
is_encumbered: ^p{
return this.current_weight > this.max_carrying_capacity;
}
}
When Properties Recalculate
Dynamic properties recalculate every time they’re accessed. This means:
-
When displayed in templates:
${player.health_percentage} -
When used in conditions:
$if(player.is_healthy) -
When accessed in JavaScript:
player.total_stats
The calculation runs fresh each time, so changes to underlying attributes automatically update derived values.
|
Tip
|
Dynamic properties are ideal for:
Avoid using them for expensive calculations that don’t change often - use regular attributes for those. |
Basic Content and Templates
The content attribute is where you define what players actually see. It uses templates that can include both static text and dynamic expressions.
Static Content
Simple text and HTML:
@card welcome {
content: ```
<h2>Welcome to the Adventure!</h2>
<p>You are standing in a medieval village square.</p>
```
}
Dynamic Content with Expressions
Use ${…} to include dynamic values:
@card status {
content: ```
<h3>Character Status</h3>
<p>Name: ${player.name}</p>
<p>Level: ${player.level}</p>
<p>Health: ${player.health}/${player.max_health}</p>
```
}
Note that expressions cannot be arbitrary pieces of Javascript so ${player.level + 1} while it will compile, is not a valid expression.
The player reference comes from bindings - you tell Rez which game objects to make available in templates:
@card status {
bindings: [player: #main_character]
content: ```
<p>Name: ${player.name}</p>
```
}
Bindings flow down so that any binding made in the @game is available in the current @scene or @card, likewise bindings in the @scene are available in the current card.
Default Bindings
Some bindings are always available:
-
card- The current card being displayed -
scene- The current scene -
game- The game object -
params- The parameters passed to the current context (for a card, the params it was played with)
@card example {
visit_count: 0
content: ```
<p>This card has been visited ${card.visit_count} times.</p>
```
}
Debugging Bindings
If you set the attribute $debug_bindings: true on any card, Rez will drop you
into the debugger to allow you to inspect the available bindings.
Navigation Between Cards
Rez provides several ways to move between cards and scenes:
Playing a Card
Use <a card="card_id"> to switch to another card in the same scene:
<a card="forest_clearing">Enter the forest</a>
This is a syntax sugar for the full form:
<a data-event="card" data-target="forest_clearing">Enter the forest</a>
You need to use the full form if returning links from user components.
Switching Scenes
Use <a scene="scene_id"> to start a new scene:
<a scene="dungeon_entrance">Enter the dungeon</a>
This is a syntax sugar for the full form:
<a data-event="switch" data-target="dungeon_entrance">Enter the dungeon</a>
You need to use the full form if returning links from user components.
Scene Interludes
Use <a interlude="scene_id> and <a resume> to run a scene interlude.
Sometimes mid-scene we find a need to go to another scene temporarily. This is very common for things like NPC conversation or combat, shops/trading or inventory management, presenting history or other details, or for mini-games.
Using an interlude we 'put a bookmark' in the current scene, switch another scene, and then use the bookmark to find our place in the original scene and continue where we left off.
<a interlude="conversation">Talk to the Hermit</a>
When the user clicks an <a resume> link the interlude scene goes away and the original scene is resumed from the point where the player left it.
These are syntax sugar for the full forms:
<a data-event="interlude" data-target="conversation">Talk to the Hermit</a> <a data-event="resume">...</a>
Controlling what happens on resume - When the original scene is resumed, Rez calls that scene’s resume_event(params) function to decide what should happen next. This function must return a RezEvent (see the event response methods listed above). By default every @scene has:
resume_event: function(params) {
return RezEvent.render();
}
which simply re-renders the current view, matching the historical resume behaviour. You can override resume_event on your own @scene to do something more elaborate, such as playing a specific card once the interlude finishes:
@scene dungeon {
resume_event: function(params) {
return RezEvent.playCard("dungeon_status");
}
}
params is whatever was passed back through the resume (e.g. via RezEvent.sceneResume()), so resume_event can vary its response based on what the interlude returned.
Event Links
Trigger custom behavior with <a event="event_name">:
@card magic_door {
locked: true
content: ```
<p>A mysterious door blocks your path.</p>
$if(card.locked) -> {%
<a event="try_key">Try to unlock with the key</a>
%}
() -> {%
<a card="beyond_door">Go through the door</a>
%}
```
on_try_key: (card) => {
if(player.has_item("magic_key")) {
card.locked = false;
return RezEvent.flash("The key works! The door swings open.");
} else {
return RezEvent.flash("You don't have the right key.");
}
}
}
|
Tip
|
Custom event handlers also receive the native click on_try_key: (card, params) => {
if(params.evt.shiftKey) {
return RezEvent.flash("You yank hard on the locked door!");
}
if(player.has_item("magic_key")) {
card.locked = false;
return RezEvent.flash("The key works! The door swings open.");
} else {
return RezEvent.flash("You don't have the right key.");
}
}
|
|
Tip
|
A big part of keeping your game managable is making good decisions about where to store the different properties that describe the 'world model'. Sometimes it is okay to put it in the nearest card but in different situations it might be more appropriate to put it elsewhere. Obvious places are the player (if you have one) or the game. However both of these can end up "stuffed" with properties relating to the world or puzzles you are setting up for the player. Sometimes you can ameliorate this with comments but often the answer is to find a better place. For example you might think about using a @object magic_door {
locked: true
description: "mysterious door"
}
If there were multiple ways that this door could be unlocked then having it contained in its own object could make a lot of sense and be much easier to understand later on. |
Buttons
You can also use buttons instead of links:
<button card="next_scene">Continue Adventure</button> <button event="cast_spell">Cast Fireball</button>
Custom Components
Rez allows you to create reusable HTML components using @component. Components are JavaScript functions that return formatted HTML and can accept parameters, making them perfect for complex UI elements that you use repeatedly.
Basic Component Syntax
@component component_name (bindings, assigns, content) => {
// JavaScript code that returns HTML string
return `<div>Custom HTML here</div>`;
}
Simple Self-Closing Component
@component health_bar (bindings, assigns, content) => {
const current = assigns.current || 0;
const max = assigns.max || 100;
const percentage = Math.round((current / max) * 100);
return `
<div class="health-bar">
<div class="health-fill" style="width: ${percentage}%"></div>
<span class="health-text">${current}/${max}</span>
</div>
`;
}
Use it in templates with dot notation as a self-closing tag:
content: ```
<.health_bar current="${player.health}" max="${player.max_health}" />
```
Container Component with Content
Components can also wrap content like regular HTML tags:
@component info_panel (bindings, assigns, content) => {
const title = assigns.title || "Information";
const type = assigns.type || "default";
return `
<div class="info-panel info-panel--${type}">
<h3 class="info-panel__title">${title}</h3>
<div class="info-panel__content">
${content}
</div>
</div>
`;
}
Use it as a container with dot notation:
content: ```
<.info_panel title="Combat Status" type="warning">
<p>You are in combat with ${enemy.name}!</p>
<p>Your health: ${player.health}</p>
</.info_panel>
```
Advanced Component with Logic
Components can include complex logic and conditionals:
@component inventory_slot (bindings, assigns, content) => {
const item = assigns.item;
const index = assigns.index;
const isEmpty = !item;
if (isEmpty) {
return `
<div class="inventory-slot inventory-slot--empty" data-slot="${index}">
<div class="slot-placeholder">Empty</div>
</div>
`;
}
const rarity = item.rarity || "common";
const quantity = item.quantity > 1 ? `<span class="quantity">${item.quantity}</span>` : "";
return `
<div class="inventory-slot inventory-slot--${rarity}" data-slot="${index}">
<img src="${item.icon}" alt="${item.name}" class="item-icon">
<div class="item-name">${item.name}</div>
${quantity}
<div class="item-tooltip" data-tooltip="${item.description}"></div>
</div>
`;
}
Component Parameters
Components receive three parameters:
-
bindings- All bindings available in the current context (player, scene, etc.) -
assigns- Attributes passed to the component via HTML attributes -
content- HTML content between opening and closing tags (for container components)
When to Use Components
Components are ideal for:
-
Repeated UI patterns - health bars, inventory slots, dialog boxes
-
Complex widgets - skill trees, character sheets, mini-maps
-
Conditional rendering - different layouts based on game state
-
Dynamic content - procedurally generated elements
-
Reusable game mechanics - card displays, battle interfaces
|
Tip
|
Keep components focused on presentation logic. For game logic, use element methods and events instead. Components work best when they transform data into HTML,rather than modify the game state. |
A Complete Example
Let’s build a simple character creation scene:
@scene character_creation {
initial_card_id: #choose_name
layout: ```
<div class="creation-scene">
<h2>Create Your Character</h2>
${content}
</div>
```
}
@card choose_name {
content: ```
<p>What is your character's name?</p>
<input type="text" rez-bind="player.name" placeholder="Enter name">
<p><button card="choose_class">Next: Choose Class</button></p>
```
}
@card choose_class {
bindings: [player: #player]
content: ```
<p>Hello, ${player.name}! Choose your class:</p>
<ul>
<li><a event="choose_warrior">Warrior (Strong and tough)</a></li>
<li><a event="choose_mage">Mage (Wise and magical)</a></li>
<li><a event="choose_thief">Thief (Quick and sneaky)</a></li>
</ul>
```
on_choose_warrior: (card) => {
player.class = "warrior";
player.strength = 15;
player.sneak = 5;
player.magic = 5;
return RezEvent.playCard("creation_complete");
}
on_choose_mage: (card) => {
player.class = "mage";
player.strength = 5;
player.sneak = 5;
player.magic = 15;
return RezEvent.playCard("creation_complete");
}
on_choose_thief: (card) => {
player.class = "thief";
player.strength = 5;
player.sneak = 15;
player.magic = 5;
return RezEvent.playCard("creation_complete");
}
}
@card creation_complete {
bindings: [player: #player]
content: ```
<h3>Character Created!</h3>
<p><strong>Name:</strong> ${player.name}</p>
<p><strong>Class:</strong> ${player.class}</p>
<p><strong>Strength:</strong> ${player.strength}</p>
<p><strong>Magic:</strong> ${player.magic}</p>
<p><button scene="game_start">Begin Adventure!</button></p>
```
}
@actor player {
$global: true
name: ""
class: ""
strength: 5
magic: 5
sneak: 5
}
This example demonstrates:
-
Multiple cards working together
-
Form input with
rez-bind -
Event handlers that modify game state
-
Dynamic content based on character attributes
-
Navigation between cards and scenes
Part 3: Building Interactive Content
Advanced Templating
Rez templates support more than just simple variable substitution. You can create dynamic content that responds to game state, user choices, and changing conditions.
Conditional Content
Use $if() expressions to show content based on conditions:
@card tavern {
bindings: [player: #hero]
content: ```
<h3>The Rusty Dragon Tavern</h3>
$if(player.gold >= 10) -> {%
<p>You have enough gold for a meal and room.</p>
<button event="buy_room">Rent a room (10 gold)</button>
%}
() -> {%
<p>You're too poor to afford a room here.</p>
<button event="work_for_gold">Offer to work for gold</button>
%}
$if(player.level >= 5) -> {%
<p>The bartender nods respectfully at such an experienced adventurer.</p>
%}
```
}
You can chain conditions:
$if(player.health <= 0) -> {%
<p>You have died!</p>
%}
(player.health < 20) -> {%
<p>You are badly wounded.</p>
%}
() -> {%
<p>You feel healthy and strong.</p>
%}
Iterating Over Collections
Use $foreach() to loop through lists or arrays:
@card inventory {
bindings: [
player: #hero,
items: (block, source, bindings) => {return $("hero").container.allItems().refs();}
]
content: ```
<h3>Your Inventory</h3>
$if(items.length > 0) -> {%
<ul>
$foreach(item: items) {%
<li>${item.name} - ${item.description}</li>
%}
</ul>
%}
() -> {%
<p>Your inventory is empty.</p>
%}
```
}
With separators between items:
$foreach(skill: player.skills) {%
${skill.name}: Level ${skill.level}
%}, {%
<br>
%}
Advanced Bindings
Bindings make data available to your templates. You can create different types of bindings:
Element Bindings - Reference game objects:
bindings: [ player: #main_character, location: #current_room, villain: #dark_lord ]
Function Bindings - Calculate values dynamically:
Function bindings receive three arguments: (block, source, bindings) where:
-
block- theRezBlockview block being rendered -
source- the game element (e.g.RezCard) that owns the template -
bindings- the bindings resolved so far (earlier entries in the list are already present)
bindings: [
total_score: (block, source, bindings) => {return bindings.player.experience + bindings.player.gold},
random_event: (_block, _source, _bindings) => {return Math.random() < 0.3},
available_exits: (_block, source, _bindings) => {return source.getExits()}
]
Dependent Bindings - Bind to attributes of another binding:
bindings: [ player: #player player_name: player.name current_health: player.health ]
Value Bindings - If you want you can bind directly to a value:
bindings: [ options: 2 ]
This is useful for giving a name to a fixed value used in your template. The value must be a literal: a string, number, boolean, keyword, or a list of these. Expressions such as 2+2 are not allowed; to compute a value, use a function binding instead.
Sharing Layouts with @layout
A scene’s layout: describes the markup wrapped around its cards. When several scenes should look the
same, define the layout once with the @layout directive and refer to it from each scene with layout_id:.
@layout l_two_column {
layout_mode: :stack
layout_separator: "<hr/>"
blocks: [sidebar: #c_sidebar]
layout: ```
<div class="columns">
<div class="column">${content}</div>
<div class="column is-3">${sidebar}</div>
</div>
```
}
@scene s_market {
layout_id: #l_two_column
initial_card_id: #c_stalls
}
@scene s_harbour {
layout_id: #l_two_column
initial_card_id: #c_quayside
bindings: [ship: #the_endeavour]
}
@layout is a directive, like @elem and @defaults, rather than an element: it exists only while your game is being compiled. The compiler copies the layout’s attributes
into every scene that refers to it, so at runtime each scene has its own layout, layout_mode and so on,
exactly as if you had written them in the scene. The layout_id attribute is removed and replaced by a
$layout_reference attribute holding the id of the layout, which error messages use to tell you which
@layout a problem came from. There is no @layout object at runtime.
A @layout has an id and a body of attributes like an element, but it can define only the following attributes and no others: layout, layout_mode, layout_separator,
layout_reverse, bindings, blocks, css_class, on_will_render and on_did_render.
Precedence. A scene’s own attributes win over its layout’s, and the layout’s attributes win over
@defaults. In order from least to most specific:
-
@defaults scene -
@defaultsfor the scene’s@elemtype, if it has one -
the
@layout -
the scene itself
So in the example above s_market could still write layout_mode: :single to change just that one thing.
Event handlers follow the same rules as @defaults: a scene that writes on_did_render: +() ⇒ {…} runs
its handler after the layout’s, while on_did_render: () ⇒ {…} replaces it.
layout_id can itself come from @defaults, for example @defaults scene { layout_id: #l_main } gives
every scene a layout unless it says otherwise.
Bindings and blocks. When both the layout and the scene define bindings: (or blocks:), the two lists
are combined instead of the scene’s replacing the layout’s. The layout’s entries come first, then the
scene’s. If the scene has an entry with the same name as one of the layout’s, the scene’s entry takes its
place. In the example above s_harbour ends up with the sidebar block from the layout and its own ship
binding.
Rules.
-
layout_idmust be a literal element id such as#l_two_column. A constant or any other kind of value is an error. -
A
@layoutcannot itself have alayout_id. Layouts do not nest. -
The
@gamecan use a@layouttoo, but only one whoselayout_modeis:single(or not given). Only thelayout,bindings,blocks,css_class,on_will_renderandon_did_renderattributes are copied into the game.
Items and Inventories
Most games need the player to carry things: a sword, a lantern, a ring, a spell they’ve learned. Rez builds this from four pieces:
-
an
@itemis something that can be held. Itstypesays what kind of thing it is. -
a
@slotis a kind of place to keep things. It says which types of item itacceptsand how much it can hold. -
an
@inventoryis a container, made up of named positions. Each position is declared with a@containsblock that says which@slotit uses. -
an
@actorcan own an inventory. Effects from the items in it, such as a ring that makes you stronger, are applied to the owner.
Items don’t have to be physical objects. A spell book can be an inventory whose items are spells, and an NPC’s memory can be an inventory whose items are conversation topics.
Items and their types
An item’s type is a keyword that connects it to the slots that can hold it. Use @derive to arrange types in a hierarchy, so that a slot that accepts a general type also accepts the more specific ones:
@derive :ring :jewellery
@derive :jewellery :item
@derive :tool :item
@item ring_of_strength {
type: :ring
name: "Ring of Strength"
weight: 0
effect_ids: [#strength_bonus]
}
@item rope {
type: :tool
name: "coil of rope"
weight: 3
size: 2
}
@item lantern {
type: :tool
name: "brass lantern"
weight: 2
}
Here a ring is jewellery, and both jewellery and tools are items. type defaults to :item. weight and size are optional and are explained below.
Slots
A @slot describes a kind of place:
@slot ring_slot {
name: "Finger"
accepts: :ring
has_capacity: true
capacity: 1
}
@slot backpack_slot {
name: "Backpack"
accepts: :item
has_capacity: true
capacity: 10
apply_effects: false
}
A ring slot only takes rings. With has_capacity: true, the size of the items in a position (1 if not given) must add up to no more than capacity, so a finger holds one ring. The backpack takes any item, because everything derives from :item, up to a total size of 10. A slot can also list other slots it excludes: for example a two-handed weapon slot could exclude the shield slot, so that only one of them can be filled.
Inventories and positions
An inventory lists its positions with @contains blocks. Each block’s id names the position, and its slot_id says which slot it uses. Several positions can use the same slot:
@inventory player_inv {
max_weight: 20
@contains left_hand {
slot_id: #ring_slot
}
@contains right_hand {
slot_id: #ring_slot
}
@contains backpack {
slot_id: #backpack_slot
contents: [#ring_of_strength #rope #lantern]
}
}
@actor player {
name: "Ada"
strength: 10
container_id: #player_inv
}
-
contentslists the items a position holds when the game begins. -
enabled: falsestarts a position locked. Unlock it later withinventory.enable("left_hand"), for example when the player reaches a certain level. -
max_weightlimits the totalweightof everything in the inventory. -
The player owns the inventory by naming it as their
container_id. In code,$("player").containeris the inventory.
Position names belong to their inventory. Every inventory can have its own left_hand, and you can’t refer to a position as an element with #left_hand. A @contains block only takes slot_id, contents, and enabled.
Working with an inventory
At runtime an inventory is a RezInventory. These are its most useful methods, where pos is a position name and item_id an item’s id:
|
the ids of the items in a position |
|
the ids of every item in the inventory |
|
which position holds an item, or |
|
put an item that isn’t anywhere yet into a position |
|
take an item out of a position |
|
move an item into a position from wherever it is: another position, another inventory, or nowhere |
|
check, unlock, or lock a position |
|
false if another occupied position’s slot excludes this one |
|
how much the inventory is carrying, and how much more it can take |
An item is only ever in one place. While it’s in an inventory, item.inventory and item.position say where. Adding an item that is already somewhere is refused; use move() instead.
add, remove, and move return a RezDecision rather than throwing an error when they can’t do what you asked. If the decision is no, nothing has changed, decision.reason explains why, and decision.getData("failed_on") says which check failed:
|
the position is disabled |
|
the item is already somewhere (from |
|
the slot doesn’t accept the item’s type |
|
another occupied position excludes this one |
|
the item is too big for the space left in the position |
|
the item would take the inventory over its |
|
the inventory’s owner refused the item (see below) |
|
the item isn’t in that position (from |
|
Tip
|
Don’t change an inventory’s |
A ring on your hand, or in your backpack
An item’s effect_ids list @effects that are applied to the inventory’s owner while the item is in a position whose slot has apply_effects (the default). The ring slot applies effects but the backpack doesn’t, so the ring only makes Ada stronger when she wears it:
@effect strength_bonus {
on_apply: (effect, event) => {
$(event.owner_id).strength += 2;
}
on_remove: (effect, event) => {
$(event.owner_id).strength -= 2;
}
}
Moving the ring from the backpack to left_hand runs on_apply, raising Ada’s strength from 10 to 12. Moving it back runs on_remove. The event also says where the item is: item_id, inventory_id, slot_id, and position.
Effects are only applied when the inventory has an owner. Set apply_effects: false on the inventory itself to turn them off for the whole inventory.
Letting an actor refuse an item
The owner gets the final say through on_accept_item, which runs after all the inventory’s own checks have passed. Its event carries a decision that defaults to yes:
@item cursed_ring {
type: :ring
name: "Ring of Woe"
}
@actor player {
...
on_accept_item: (player, event) => {
if(event.item_id === "cursed_ring" && event.position !== "backpack") {
event.decision.no("you feel a chill and think better of it");
}
}
}
Ada will carry the cursed ring but won’t put it on.
Reacting to changes
Adding an item runs an insert event on the inventory, then the item’s slot, then the item. Removing it runs remove on the slot, then the item, then the inventory. Each gets the same event:
{
inventory_id: <id>,
slot_id: <id of the position's @slot>,
position: <name of the position>,
item_id: <id>,
owner_id: <id, or null if the inventory has no owner>,
owner: <the owning actor, or null>
}
So on_insert on an item can react to being picked up, and on_insert on a slot can react to anything put in a position that uses it. Every change to an inventory also runs its on_positions_changed handler.
An inventory card
Putting it together, this card lists the backpack, with a link to wear each item. The item’s id is passed to the event handler in a data-item attribute:
@card c_backpack {
bindings: [
player: #player
backpack: (block, source, bindings) => {return $("player_inv").itemsIn("backpack").refs()}
]
content: ```
<p>${player.name} has a strength of ${player.strength}.</p>
$if(backpack.length > 0) -> {%
<ul>
$foreach(item: backpack) {%
<li>${item.name} <a data-event="wear" data-item="${item.id}">Wear</a></li>
%}
</ul>
%}
() -> {%
<p>Your backpack is empty.</p>
%}
```
on_wear: (card, params) => {
const inv = $("player_inv");
let decision = inv.move("left_hand", params.item);
if(decision.wasNo && decision.getData("failed_on") === "capacity") {
decision = inv.move("right_hand", params.item);
}
if(decision.wasNo) {
return RezEvent.flash(`You can't wear that: ${decision.reason}`);
}
return RezEvent.render();
}
}
itemsIn() returns ids, and refs() turns a list of ids into the objects themselves so the template can use item.name. The handler tries the left hand and, if it’s full, the right. Wearing the rope gives "You can’t wear that: position doesn’t take this kind of item".
For every attribute of @inventory, @slot, and @item, see the Element Catalog. For every method, see the RezInventory API documentation.
Forms and User Input
Rez makes it easy to capture user input through HTML forms with two-way data binding.
Text Input
Use the rez-bind={id.attr} syntax to create a two way binding between a text input and a compatible attribute. In this example
we bind player.name to a text input and player.background to a textarea. The form field will initially take on the value of
the attribute. Changes to the form field will be transparently applied to the attribute.
@card character_setup {
bindings: [player: #player]
content: ```
<h3>Character Setup</h3>
<label>Character Name:</label>
<input type="text" rez-bind="player.name" placeholder="Enter your name">
<label>Background Story:</label>
<textarea rez-bind="player.background" rows="4"></textarea>
<button card="choose_stats">Continue</button>
```
}
Checkboxes and Choices
Similarly you can use rez-bind to bind checkboxes to boolean attribute values.
@card preferences {
bindings: [settings: #game_settings]
content: ```
<h3>Game Preferences</h3>
<label>
<input type="checkbox" rez-bind="settings.sound_enabled">
Enable Sound Effects
</label>
<label>
<input type="checkbox" rez-bind="settings.difficulty_hard">
Hard Difficulty Mode
</label>
```
}
Radio buttons for exclusive choices:
<h4>Choose your weapon:</h4> <label> <input type="radio" name="weapon" value="sword" rez-bind="player.starting_weapon"> Sword (+3 Attack) </label> <label> <input type="radio" name="weapon" value="bow" rez-bind="player.starting_weapon"> Bow (+2 Attack, +1 Range) </label> <label> <input type="radio" name="weapon" value="staff" rez-bind="player.starting_weapon"> Staff (+1 Attack, +2 Magic) </label>
Select Dropdowns
For choosing from many options:
<label>Starting Location:</label> <select rez-bind="player.hometown"> <option value="village">Peaceful Village</option> <option value="city">Bustling City</option> <option value="forest">Forest Dwelling</option> <option value="mountain">Mountain Keep</option> </select>
Event-Driven Forms
Use rez-live to trigger events when form values change:
@card dynamic_stats {
content: ```
<h3>Allocate Stat Points</h3>
<p>Points remaining: ${card.points_remaining}</p>
<label>Strength:
<input type="range" min="1" max="20" rez-bind="player.strength" rez-live>
</label>
<label>Intelligence:
<input type="range" min="1" max="20" rez-bind="player.intelligence" rez-live>
</label>
```
points_remaining: 20
on_input: (card, event) => {
const total = player.strength + player.intelligence;
card.points_remaining = 20 - total;
return RezEvent.render();
}
}
Form Submission
A form with the rez-live attribute and a name raises an event when it is submitted, either by clicking a submit button or by pressing Enter in one of its inputs. The event handler is the on_ attribute matching the form’s name, so <form name="login"> runs on_login.
@card login {
content: ```
<form name="login" rez-live>
<input type="text" name="user" placeholder="Your name">
<button type="submit">Go</button>
</form>
```
on_login: (card, evt) => {
const data = new FormData(evt.form);
player.name = data.get("user");
return RezEvent.playCard("c_welcome");
}
}
The handler receives the object that handled the event and an event object whose form property is the DOM form element. Like any other event script it must return a RezEvent; if it returns nothing the event is treated as RezEvent.noop().
Rez looks for the handler on the card containing the form first and then, as with other events, on the current card, the scene, and the game. The form must have a name, otherwise Rez raises a "Cannot get form name!" error. If no handler is found nothing happens.
|
Tip
|
Fields with |
Assets and Media
Add images, audio, and other media to your games using the asset system.
Defining Assets
Create asset elements to register your media files. Put the files in your game’s assets/ folder and refer to each one with either file_name (the compiler searches assets/ and its subfolders for a file with that name) or file_path (a path relative to assets/), but not both:
@asset hero_portrait {
file_name: "hero.png"
width: 150
height: 200
}
@asset background_music {
file_path: "audio/tavern_theme.mp3"
}
@asset treasure_sound {
file_path: "audio/treasure_found.wav"
}
width and height must be given together. The compiler copies each asset into the dist folder and fails if a file can’t be found.
Using Images
Display images in your content with the <.img> component. It uses the asset’s width and height unless you give it others, and passes any other attributes on to the <img> tag:
@card character_sheet {
content: ```
<h3>Character Information</h3>
<div class="character-display">
<.img name="hero_portrait" class="character-image" />
<div class="character-stats">
<p><strong>Name:</strong> ${player.name}</p>
<p><strong>Level:</strong> ${player.level}</p>
</div>
</div>
```
}
Or build your own image tags. An asset’s $dist_path attribute is the path of its file in the built game:
@card portrait {
bindings: [hero_portrait: #hero_portrait]
content: ```
<img src="${hero_portrait.$dist_path}" alt="Hero Portrait" class="portrait">
```
}
Dynamic Assets
Choose different assets based on game state. A component attribute written as {…} is a JavaScript expression evaluated with the template’s bindings:
@card location_view {
bindings: [
location_image: (block, source, bindings) => {
if (player.location === "forest") return "forest_scene";
if (player.location === "dungeon") return "dungeon_scene";
return "default_scene";
}
]
content: ```
<div class="location-display">
<.img name={location_image} alt="Current Location" />
</div>
```
}
Audio Integration
While audio isn’t fully integrated yet, you can add it manually:
@card victory {
bindings: [music: #victory_music]
content: ```
<h2>Victory!</h2>
<p>You have defeated the dragon and claimed the treasure!</p>
<audio autoplay>
<source src="${music.$dist_path}" type="audio/mpeg">
</audio>
```
}
Fonts
To use a font from a hosted service such as Google Fonts, add its stylesheet URL to the @game links: attribute and refer to the family in @styles:
@game {
links: ["https://fonts.googleapis.com/css2?family=Crimson+Pro:ital,wght@0,400;1,400&display=swap"]
}
@styles {
body { font-family: "Crimson Pro", serif; }
}
To bundle a font with your game, put the file (.woff2, .woff, .ttf or .otf) in assets/ and give its @asset a font_family:. The compiler copies the file and writes the @font-face rule for you. Make one asset for each weight and style:
@asset font_body {
file_name: "CrimsonPro-Regular.woff2"
font_family: "Crimson Pro"
$preload: true
}
@asset font_body_italic {
file_name: "CrimsonPro-Italic.woff2"
font_family: "Crimson Pro"
font_style: "italic"
}
@styles {
body { font-family: "Crimson Pro", serif; }
}
font_weight: defaults to 400 and can be a number or, for a variable font, a range such as "100 900". font_style: ("normal", "italic" or "oblique") defaults to "normal", and font_display: ("auto", "block", "swap", "fallback" or "optional") defaults to "swap". $preload: true adds a <link rel="preload"> so the browser fetches the font straight away; use it for the fonts your first screen needs. $inline: true embeds the font in index.html as a data: URL instead of copying the file.
|
Note
|
When you open a game straight from disk (a file:// URL), the browser console may warn that a preloaded font "is not used because the request credentials mode does not match", or was "preloaded using link preload but not used". The browser loads fonts from file:// pages differently, so it can’t reuse the preloaded copy and fetches the font again. The font still works. The warnings go away when the game is served over http(s), e.g. by running python3 -m http.server in the dist folder. To silence them while developing, leave out $preload: true. If the second warning appears over http(s) too, nothing on the first screen uses that font, so it doesn’t need preloading.
|
A font asset without font_family: is copied but gets no @font-face rule. To write your own rule in @styles, refer to the file with asset(id), e.g. src: asset(font_body) format("woff2"); (see Adding Custom CSS).
To change fonts for a scene or card, use CSS: give the scene’s layout a class and style it in @styles.
Building a Complete Interactive Scene
Let’s create a combat system that demonstrates advanced templating and dynamic content:
@scene combat {
initial_card_id: #combat_start
enemy_id: #goblin
bindings: [
player: #player
enemy: scene.enemy
]
layout: ```
<div class="combat-scene">
<h2>Combat!</h2>
${content}
</div>
```
}
@card combat_start {
content: ```
<div class="combat-status">
<div class="combatant">
<h4>${player.name}</h4>
<div class="health-bar">
<div class="health-fill" style="width: ${player.health_perc}%"></div>
</div>
<p>Health: ${player.health}/${player.max_health}</p>
</div>
<div class="vs">VS</div>
<div class="combatant">
<h4>${enemy.name}</h4>
<div class="health-bar">
<div class="health-fill" style="width: ${enemy.health_perc}%"></div>
</div>
<p>Health: ${enemy.health}/${enemy.max_health}</p>
</div>
</div>
<div class="combat-actions">
<h4>Choose your action:</h4>
<button event="attack">Attack (${player.attack_power} damage)</button>
<button event="defend">Defend (+${player.defense_bonus} defense)</button>
$if(player.mana >= 10) -> {%
<button event="cast_spell">Cast Fireball (10 mana)</button>
%}
<button event="try_flee">Attempt to Flee</button>
</div>
```
on_attack: (card) => {
const enemy = card.scene.enemy;
const damage = Math.max(1, $player.attack_power - enemy.defense);
enemy.health -= damage;
if (enemy.health <= 0) {
return RezEvent.playCard("victory");
} else {
return RezEvent.playCard("enemy_turn").flash(`You deal ${damage} damage!`);
}
}
on_defend: (card) => {
$player.temp_defense = $player.defense_bonus;
return RezEvent.playCard("enemy_turn").flash("You prepare to defend!");
}
on_cast_spell: (card) => {
const enemy = card.scene.enemy;
$player.mana -= 10;
const damage = 15;
enemy.health -= damage;
if(enemy.health <= 0) {
return RezEvent.playCard("victory");
} else {
return RezEvent.playCard("enemy_turn").flash(`Your fireball deals ${damage} damage!`);
}
}
on_try_flee: (card) => {
const flee_ability = 0.5 * (($player.sneak - 7.5) / 7.5);
const flee_chance = 0.5 + flee_ability;
if (Math.random() < flee_chance) {
return RezEvent.sceneChange("overworld").flash("You successfully escape!");
} else {
$player.temp_defence = -5;
return RezEvent.playCard("enemy_turn").flash("You couldn't escape!");
}
}
}
@card enemy_turn {
content: ```
<p>${enemy.name} attacks!</p>
<button event="continue">Continue</button>
```
on_continue: (card) => {
const enemy = card.scene.enemy;
const damage = Math.max(1, enemy.attack_power - ($player.defense + ($player.temp_defense || 0)));
player.health -= damage;
player.temp_defense = 0; // Reset temporary defense
if (player.health <= 0) {
return RezEvent.playCard("defeat");
} else {
return RezEvent.playCard("combat_start").flash(`${enemy.name} deals ${damage} damage to you!`);
}
}
}
@card victory {
content: ```
<h3>Victory!</h3>
<p>You have defeated the ${enemy.name}!</p>
<p>You gain ${enemy.experience_reward} experience and ${enemy.gold_reward} gold.</p>
<button scene="overworld">Continue your adventure</button>
```
on_start: (card) => {
const enemy = card.scene.enemy;
player.experience += enemy.experience_reward;
player.gold += enemy.gold_reward;
}
}
@actor player {
$global: true
name: "Hero"
health: 100
max_health: 100
health_perc: ^p{
return this.health * 100 / this.max_health;
}
mana: 50
attack_power: 15
defense: 5
defense_bonus: 3
experience: 0
gold: 0
}
@actor goblin {
$global: true
name: "Goblin"
health: 30
max_health: 30
health_perc: ^p{
return this.health * 100 / this.max_health;
}
attack_power: 8
defense: 2
experience_reward: 25
gold_reward: 10
}
This combat system demonstrates:
-
Dynamic health bars using CSS and template expressions
-
Conditional action availability based on resources (mana)
-
Bindings flowing down from scene to card
-
Dynamic properties
-
Event-driven gameplay with multiple outcomes
-
State management across multiple cards
-
Visual feedback through flash messages
Part 4: Advanced Features
Custom Elements and Mixins
As your games grow more complex, you’ll want to create your own element types and reusable components.
Creating Custom Elements
Use @elem to define new element types based on existing ones:
@elem npc = actor
@npc village_guard {
name: "Guard"
occupation: "Village Protector"
dialogue: "Halt! State your business."
}
This creates a new @npc element type that inherits all the properties of @actor but can have its own defaults and behaviors.
Adding Default Attributes
Use @defaults to give custom elements standard attributes:
@elem monster = actor
@defaults monster {
hostile: true
experience_reward: 10
gold_reward: 5
behavior_pattern: :aggressive
}
@monster goblin {
name: "Goblin Warrior"
health: 25
attack_power: 8
%% Inherits: hostile: true, experience_reward: 10, etc.
}
Testing "types"
Rez doesn’t have types in a programming language sense, @elem aliases always
resolve, possibly through other aliases, to one of Rez’s built-in element types
such as @actor, @card or @object. What varies is the attributes and defaults
that are applied to that object.
Nevertheless, from time to time, you want to test the "type" of a given object,
for example to return a list of all @monster elements. Rez provides the kindOf() method for this purpose.
@elem npc = actor
@elem monster = npc
@monster troll {...}
@npc guard {...}
@game {
monsters: function() {
return $game.filterObjects((obj) => obj.kindOf("monster"));
}
}
Mixins for Shared Behavior
Mixins are another way to share behaviour across different element types. They work by injecting functions and dynamic properties (^p{…}) into objects at runtime. A mixin only provides functions and ^p{…} properties: plain values such as health: 100 in a mixin are ignored. Give elements their data with @defaults instead.
@mixin combat_capable {
is_dead: ^p{
return this.health <= 0;
}
take_damage: function(amount) {
this.health = Math.max(0, this.health - amount);
return this.is_dead;
}
heal: function(amount) {
this.health = Math.min(this.max_health, this.health + amount);
}
}
@elem warrior = actor
@defaults warrior {
$mixins: #{#combat_capable}
health: 100
max_health: 100
attack_power: 10
defense: 5
}
@warrior player_character {
name: "Hero"
%% Gets the combat_capable methods and the warrior defaults
}
Multiple mixins can be combined:
@mixin magic_user {
cast: function(cost) {
if(this.mana < cost) {
return false;
}
this.mana -= cost;
return true;
}
}
@warrior battle_mage {
$mixins: #{#combat_capable #magic_user}
mana: 50
max_mana: 50
spell_power: 12
}
Behavior Trees
For complex NPC AI and game logic, Rez includes a powerful behavior tree system. Behavior trees let you create sophisticated, reactive AI without writing complex JavaScript.
Basic Behavior Tree Concepts
Behavior trees are composed of nodes that either succeed or fail:
-
Composite nodes coordinate multiple child behaviors
-
Condition nodes test the game state
-
Action nodes modify the game state
@actor smart_guard {
name: "Intelligent Guard"
behaviours: ^[
$select
[$sequence
[player_nearby range=3]
[guard_not_alerted]
[set_alert_level level=1]]
[$sequence
[alert_level_equals level=2]
[call_for_backup]]
[patrol_route]
]
}
The tree is written in the behaviours attribute. At runtime the attribute holds the root behaviour of the tree, with the actor as its owner, and you run the tree by calling executeBehaviour() on it:
$("smart_guard").behaviours.executeBehaviour();
The stdlib also includes a $actor_behaviours system, disabled by default, that runs the behaviours tree of every actor when a behaviours event is raised (for example by <a event="behaviours">). Set enabled: true on it to use it.
Core Behavior Types
$select - Try children until one succeeds (OR logic):
behaviours: ^[
$select
[has_weapon] %% Try this first
[find_weapon] %% If no weapon, try to find one
[flee_combat] %% Last resort: run away
]
$sequence - All children must succeed (AND logic):
behaviours: ^[
$sequence
[see_enemy] %% First, spot an enemy
[weapon_ready] %% Then, make sure weapon is ready
[attack_enemy] %% Finally, attack
]
The stdlib defines these core behaviours. Their ids begin with $:
|
run children in order (or in random order for |
|
like |
|
run children in order; fails as soon as one fails |
|
run its one child |
|
run its one child up to |
|
run its one child if a |
|
run its first child if a |
|
run one child chosen at random ( |
|
run its one child and then succeed, fail, or invert the result |
|
succeed or fail without doing anything |
Options are given in the tree as name=value, for example [$maybe p=25 [shout]].
Writing Custom Behaviors
Create your own condition and action behaviors. A behaviour’s execute function is passed one argument, the behaviour itself, and must return true if it succeeds or false if it fails. Any other return value raises an error. The behaviour gives access to:
-
behaviour.owner- the element whose tree this is, e.g. the actor -
behaviour.option("name"),behaviour.intOption("name"),behaviour.numberOption("name")- the options given in the tree -
behaviour.childrenandbehaviour.firstChild- child behaviours, each of which can be run withexecuteBehaviour()
options_spec lists the names of the options the behaviour uses, as keywords. Any state that must last between runs of the tree belongs in the world model, for example in attributes of the owner.
@behaviour player_nearby {
options_spec: [:range]
execute: (behaviour) => {
// distanceTo() is a method you would define on your actors
const distance = behaviour.owner.distanceTo($("player"));
return distance <= behaviour.intOption("range");
}
}
@behaviour set_alert_level {
options_spec: [:level]
execute: (behaviour) => {
behaviour.owner.alert_level = behaviour.intOption("level");
return true;
}
}
Complex AI Example
Here’s a sophisticated NPC that reacts to the player and environment:
@actor tavern_keeper {
name: "Bartender Bob"
mood: :neutral
reputation_with_player: 0
last_interaction: 0
behaviours: ^[
$select
%% Emergency responses
[$sequence
[tavern_on_fire]
[evacuate_tavern]]
%% Player interactions
[$sequence
[player_at_bar]
[$select
[$sequence
[player_reputation_high]
[greet_warmly]]
[$sequence
[player_reputation_low]
[greet_coldly]]
[greet_neutrally]]]
%% Idle behaviors
[$sequence
[no_customers_present]
[$select
[clean_glasses]
[restock_bottles]
[count_money]]]
%% Default: serve customers
[serve_random_customer]
]
}
@behaviour player_at_bar {
execute: (behaviour) => {
return $("player").location_id === "tavern_bar";
}
}
@behaviour greet_warmly {
execute: (behaviour) => {
const greetings = [
"Welcome back, friend! The usual?",
"Good to see you again! What can I get you?",
"My favorite customer! What brings you here today?"
];
const keeper = behaviour.owner;
keeper.current_dialogue = greetings.randomElement();
$game.addFlashMessage(`${keeper.name} says: ${keeper.current_dialogue}`);
return true;
}
}
Custom Scripts and Styles
Extend Rez with your own JavaScript functions and CSS styling.
Adding Custom JavaScript
Use @script to add utility functions:
@script {
// Dice rolling utilities
function rollDie(sides) {
return Math.floor(Math.random() * sides) + 1;
}
function rollDice(count, sides, modifier = 0) {
let total = modifier;
for (let i = 0; i < count; i++) {
total += rollDie(sides);
}
return total;
}
// Combat calculation helpers
function calculateDamage(attacker, defender) {
const baseDamage = rollDice(2, 6) + attacker.strength_modifier;
const mitigatedDamage = Math.max(1, baseDamage - defender.armor_class);
return mitigatedDamage;
}
}
Adding Custom CSS
Use @styles to style your game:
@styles {
.character-sheet {
border: 2px solid #8B4513;
border-radius: 10px;
padding: 20px;
background: linear-gradient(135deg, #F5E6D3, #E8D5B7);
box-shadow: 0 4px 8px rgba(0,0,0,0.3);
}
.health-bar {
width: 100%;
height: 20px;
background-color: #444;
border: 2px solid #000;
border-radius: 10px;
overflow: hidden;
}
.health-fill {
height: 100%;
background: linear-gradient(90deg, #ff4444, #ffaa44, #44ff44);
transition: width 0.3s ease;
}
.combat-actions button {
background: #8B4513;
color: white;
border: none;
padding: 10px 20px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
.combat-actions button:hover {
background: #A0522D;
transform: translateY(-2px);
}
.flash-message {
background: #FFD700;
border: 2px solid #FFA500;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
text-align: center;
font-weight: bold;
}
}
To use an asset’s file in CSS, write asset(id) wherever CSS expects a url(…). The compiler replaces it with the URL of the asset in the built game, and fails if the id is not an asset:
@asset img_parchment {
file_path: "images/parchment.png"
}
@asset cur_compass {
file_path: "cursors/compass.png"
}
@styles {
.card { background-image: asset(img_parchment); }
.map { cursor: asset(cur_compass), auto; }
}
asset(img_parchment) becomes url("assets/images/parchment.png"), or a data: URL if the asset has $inline: true.
JavaScript Patches
Extend built-in JavaScript objects with the @patch directive:
@patch {
patch: "Array"
method: "sample"
impl: function(count = 1) {
const shuffled = [...this].sort(() => 0.5 - Math.random());
return count === 1 ? shuffled[0] : shuffled.slice(0, count);
}
}
%% Now you can use:
%% ["red", "green", "blue"].sample() -> "green"
%% [1,2,3,4,5].sample(3) -> [3, 1, 5]
Custom Template Filters
Create your own template expression filters:
@filter DICE_ROLL_FILTER {
name: "roll"
impl: (dice_notation) => {
// Parse "2d6+3" format
const match = dice_notation.match(/(\d+)d(\d+)(?:\+(\d+))?/);
if (!match) return 0;
const count = parseInt(match[1], 10);
const sides = parseInt(match[2], 10);
const modifier = parseInt(match[3], 10) || 0;
return rollDice(count, sides, modifier);
}
}
%% Use in templates:
%% <p>You rolled ${"2d6+3" | roll} damage!</p>
Part 5: Technical Reference
How Rez Works Under the Hood
Understanding Rez’s compilation and runtime process helps you debug issues and optimize your games.
The Compilation Process
When you run rez compile, several steps occur:
-
Parse Source Files - Rez reads your
.rezfiles and parses the element definitions -
Validate References - Checks that element references (like
#player) point to existing elements -
Generate JavaScript - Converts elements into JavaScript objects and classes
-
Template Compilation - Transforms template expressions into rendering functions
-
Asset Processing - Copies assets and generates asset manifests
-
Runtime Assembly - Combines everything into
runtime.jsandindex.html
Runtime Object Model
Your Rez elements become JavaScript objects at runtime:
-
@game→RezGameinstance -
@scene→RezSceneinstance -
@card→RezCardinstance -
@actor→RezActorinstance -
And so on…
Each object gets methods and properties based on the attributes you defined:
@actor hero {
name: "Brave Knight"
health: 100
heal: function(amount) {
this.health += amount;
}
}
// Becomes at runtime:
const hero = new RezActor({
id: "hero",
name: "Brave Knight",
health: 100,
heal: function(amount) {
this.health += amount;
}
});
The Rendering Pipeline
Content rendering follows this flow:
-
Game Layout renders with scene content in
${content} -
Scene Layout renders with card content in
${content} -
Card Content renders with template expressions resolved
-
Blocks (if any) render and provide additional template variables
Each level wraps the next in HTML structure:
<div class="game"> <!-- Game wrapper -->
<!-- Game layout content -->
<div class="scene" id="scene_forest"> <!-- Scene wrapper -->
<!-- Scene layout content -->
<div class="card" id="card_clearing"> <!-- Card wrapper -->
<!-- Card content -->
</div>
</div>
</div>
Memory and Performance
Global Objects: Elements with $global: true become window variables:
@actor player {
$global: true
name: "Hero"
}
%% Accessible as: window.$player or just $player
Template Caching: Template rendering functions are compiled once and cached for performance.
Event Delegation: Rez uses event delegation for clicks, so dynamically added content automatically works.
Saving and Loading
Rez can save the state of a game to a JSON file and restore it later. Call $game.save() to download
a save file and $game.load(json) to restore one. The standard library’s $load_game scene provides
a file upload form that does this for the player. A game cannot be saved while an interlude is being
shown ($game.canSave is false) and calling $game.save() then raises an error.
Rez does not save the whole game. The game is built from your source every time it starts, so a save file only has to record what has changed since then. When the game is saved, the changed attributes of each object are written to the file and objects with no changed attributes are left out. When a save is loaded the saved attributes are assigned to the freshly built objects.
An attribute counts as changed when it is assigned, for example player.score = 10 or
player.score += 1. Changing the contents of a list, set or record is different, see
Changing Collections in Place below.
Lists, records, sets and element ids are saved and restored as they are, including when they are nested inside one another.
|
Note
|
Save files written by older versions of Rez recorded every set as an empty record. Loading
one of those files keeps each object’s tags as defined in your source, but any other set it contains
loads as an empty record.
|
Archive Format
The archive_format attribute of the @game is a version number for the saved state of your game.
A save file can only be loaded by a game with the same archive_format, otherwise loading raises an
error. Increase it when you change your game in a way that would make existing saves wrong, for example
by renaming or removing attributes that are saved.
Save and Load Events
Objects receive an on_will_save event just before the save file is written and an on_did_load
event after their saved attributes have been restored.
Leaving Attributes Out
Some attributes are transient, for example data that is regenerated every time a card starts. List
them in the $no_archive attribute, a set of attribute names, and they are left out of save files.
@card combat {
$no_archive: #{:enemy_list :turn_order}
enemy_list: []
turn_order: []
on_start: (card, event) => {
card.enemy_list = generateEnemies();
card.turn_order = calculateTurnOrder(card.enemy_list);
return RezEvent.render();
}
}
Changing Collections in Place
|
Warning
|
Rez only knows that an attribute has changed when it is assigned. It cannot see what you do inside a list, set or record, so none of these mark the attribute as changed: player.visited.push(location); // or pop, shift, unshift, splice, sort, reverse
player.traits[0] = trait;
player.flags.door_open = true; // setting a key in a record
player.visited.add("cave"); // adding to a set
player.favourites.remove(item); // library methods like remove(), take() and fyShuffle()
If the attribute is not assigned anywhere else, the change is silently left out of saved games. The game plays correctly until it is saved and loaded, and then the change is gone. |
There are three ways to avoid this.
modifyAttribute (recommended). Pass the name of the attribute and a function that changes it. Rez
flags the attribute as changed and then calls your function with the attribute’s current value. Whatever
the function returns is returned to you:
player.modifyAttribute("visited", (visited) => visited.push(location));
player.modifyAttribute("flags", (flags) => { flags.door_open = true; });
const [removed] = player.modifyAttribute("favourites", (favourites) => favourites.splice(index, 1));
modifyAttribute raises an error if the object has no attribute with that name, so a misspelling is
caught instead of silently doing nothing.
Assign a new value. Build a new collection instead of changing the old one and assign it:
player.visited = [...player.visited, location];
player.favourites = player.favourites.filter((i) => i !== favourite);
player.flags = {...player.flags, door_open: true};
Assignment is the only approach that also runs the on_<attribute>_changed handler, notifies
observers, updates bound form controls and records the change so it can be undone. If you want any of
those, assign. Assigning the same collection back after changing it (player.inventory = player.inventory)
does get it saved, but the old and new values are then the same object, so undo cannot restore the
previous contents.
markChanged. When the change is made somewhere else, for example by a function that is handed
the list, call markChanged with the attribute name afterwards:
player.deck.fyShuffle();
player.markChanged("deck");
modifyAttribute and markChanged only affect saving. They do not run on_<attribute>_changed,
notify observers, update bound controls or record the change for undo.
|
Note
|
A save file holds the current value of every attribute that has ever been assigned or flagged, so once an
attribute has been assigned (or flagged) once, later in-place changes to it are saved too. Don’t rely on
this. It makes the problem intermittent, and an attribute that only ever receives in-place changes, for
example one defined as |
Complete Attribute Type Reference
Primitive Types
Boolean
visible: true completed: false enabled: yes %% yes/no also work hidden: no
Number
count: 42 price: 19.99 temperature: -10 percentage: 0.85
String
name: "Magic Sword" description: "A blade that glows with inner light" note: "" %% Empty string
Keyword
type: :weapon rarity: :legendary status: :active category: :consumable
Complex Types
Element Reference
owner_id: #player location_id: #forest_clearing target_id: #dragon
List (space-separated, no commas)
colors: [:red :green :blue] scores: [100 250 75 420] items: [#sword #shield #potion] mixed: ["text" 42 :keyword #reference]
Set (unique values, unordered)
tags: #{:magical :rare :weapon}
visited_locations: #{#town #forest #cave}
Template (multi-line with expressions)
content: ```
<h2>${title}</h2>
<p>Welcome, ${player.name}!</p>
$if(player.level > 5) -> {%
<p>You are an experienced adventurer.</p>
%}
```
Binding List (key-value pairs)
bindings: [
player: #main_character,
location: (block, source, bindings) => {return bindings.player.current_location;},
gold: player.gold,
items: *player.item_ids
]
A function binding’s body must be wrapped in braces with an explicit return. (b, s, bs) ⇒ bs.player.gold is not accepted.
A * before a path turns the element id, or list of ids, it refers to into the element object(s). Use it when a template needs the objects themselves, for example to loop over them with $foreach.
Special Value Types
Dynamic Initializer
When you want to initialize an attribute with a dynamic value, but have it respond
with the same value thereafter you use the dynamic initializer ^init (^i for short).
This is followed by a Javascript expression wrapped in {} that returns the value
used to initialize the attribute.
Thereafter the attribute is equivalent to a statically declared value and can be changed or replaced as normal.
You may optionally specify a priority 1-10 for the initializer, :n, that determines
when it runs relative to other initializers. If left unspecified initializers get a
default priority of 10, the lowest, meaning that they run after all other initializers.
Within a priority level no ordering of initializers is guaranteed.
@object treasure_horde {
gold: ^init:1{return Math.rand_int_between(20, 50);}
silver: ^i:2{return Math.rand_int_between(this.gold, 200);}
copper: ^init{return Math.rand_int_between(this.silver, 1000);}
}
In the example the gold initializer has priority 1 and runs first. This means
that when the silver initializer runs at priority 2 the object has its
gold property set and it can depend upon that value. The copper initializer
runs at the default priority of 10 which guarantees that the silver value
is alos avialable.
Note that initializers must return a value. The runtime turns initializers into
functions run during game initialization. During an initializer the value of
this is the element whose attribute value is being initialized.
Dynamic Property
When you want an attribute whose value is computed whenever it is accessed you use
a dynamic property ^prop (^p for short).
This is followed by a Javascript expression wrapped in {} that returns the value
of the property at that time.
@actor player {
movement_speed: ^p{
let speed = this.base_speed || 30;
if(this.is_encumbered) {
speed = Math.floor(speed / 2);
}
if(this.hasCondition?.("haste")) {
speed *= 2;
} else if (this.hasCondition?.("slow")) {
speed = Math.floor(speed / 2);
}
return Math.max(0, speed);
}
}
In this example whenever speed is requested it will be recalculated and that value
returned.
@card c_player_run {
bindings: [
player: #player
]
content: ```
<p>Your character can run at ${player.speed} meters per second.</p>
```
}
Delegation
When you want an attribute value that is a short-cut for an attribute value of a
composed object you use the delegation operator ^del (^d for short).
This is followed by : and the name of an element reference attribute (without
its _id suffix). The attribute is looked up on the object that reference points
to, and its value is returned.
Delegate Lookup (referenced in a component element)
When you want to simplify how you refer to an attribute in a composed element,
use a ^d:attr property.
@actor player {
spells_cast: ^d:spell_book
spell_book_id: #player_spell_book
}
@object player_spell_book {
spells_cast: 0
}
In the example we can refer directly to player.spells_cast and it will forward
that to its spell_book attribute which should be an element reference attribute
of the same element.
This is a syntactic sugar that is equivalent to player.spell_book.spells_cast.
Copy Initializer (copies an element template)
When you want to compose two elements by assigning a copy of a template element
to an attribute use the ^c:#<id_ref> copy initializer.
During initialization the specified element will be copied and added to the game and the id of the copy will be assigned to the named attribute.
You may optionally specify a priority 1-10 for the copy initializer, :n, that
determines when it runs relative to other initializers. If left unspecified copy
initializers get priority 10, the lowest priority.
@item sword_template {
$template: true
damage: ^i{return Math.rand_int_between(6, 8)}
name: "Iron Sword"
}
@actor player {
weapon_id: ^c:#sword_template
}
During initialization sword_template will be copied and the id of the copy
will be assigned to the player weapon_id. From that point player.weapon
will refer to the specific copy and not the template.
The copy process sets $template: false on the new object and adds a
$original_id attribute containing the id of the source element. Any
initializers on the copied element (such as the damage initializer above)
will run during the copy, so each copy gets its own independent values.
After copying, the copy event fires on the new object with {original: <source>}
allowing custom post-copy setup.
@item weapon_template {
$template: true
on_copy: (obj, evt) => {
console.log(`Created ${obj.id} from ${evt.original.id}`);
}
}
@actor hero {
main_hand_id: ^c:1:#weapon_template
off_hand_id: ^c:2:#weapon_template
}
In this example, main_hand_id has priority 1 and initializes first, then
off_hand_id at priority 2. Each gets an independent copy of the template.
Note: Copy initializers run before delegate (^d) and dynamic (^i) initializers,
so copied elements are available when those initializers execute.
^copy is accepted as a longer alias for ^c, e.g. ^copy:#sword_template.
Customising the copy
A copy initializer can be followed by a block of JavaScript that customises the copy, for example to override some of the attributes it inherits from the template:
@actor hero {
weapon_id: ^c:#sword_template{copy.name = "Excalibur"; copy.damage = 12;}
shield_id: ^c:2:#shield_template{
copy.name = "Hero's Shield";
copy.armour = copy.armour + 2;
}
}
The block must come immediately after the element id, with no whitespace between
the id and the opening {.
The block is the body of a function that receives two parameters:
-
copy— the newly created copy -
owner— the element whose attribute is being initialized
The function is passed to addCopy() as its post_init_fn (see
Procedural Generation), which determines when it runs:
-
The template is copied and the copy’s
init()runs, so the copy’s own initializers (e.g.^i,^r) and itson_inithandler have already run. Any value you assign therefore replaces the one the template’s initializer produced, and plaincopy.attr = valueassignment works as normal. -
The block runs.
-
The
copyevent fires, so anon_copyhandler sees the values the block set.
The block contains statements, not an attribute map. There is no declarative
{name: "Excalibur"} override form, so write copy.name = "Excalibur";. Its
return value is ignored.
Use owner rather than looking the owning element up by id. When the owner is
itself a copy of a template, it has an automatically generated id, so its id isn’t
known when you write the block. Copy initializers don’t run on $template: true
elements, only on their copies, so owner is always the copy being built:
@item T_sword {
$template: true
damage: 6
}
@elem monster = actor
@defaults monster {
$template: true
weapon_id: ^c:#T_sword{copy.damage = copy.damage + owner.tier * 2;}
}
@monster T_goblin {
tier: 1
}
@monster T_ogre {
tier: 3
}
Every monster created with $("T_goblin").addCopy() or $("T_ogre").addCopy()
gets its own sword. Each sword’s damage is based on the tier of the monster
that owns it, so goblin swords do 8 damage and ogre swords do 12.
While the block runs, the owner is only partly initialized:
-
The owner’s static attributes, and attributes from copy initializers with a higher priority (a lower number), are available.
-
The attribute being initialized is set only after the block returns, so
owner.weapon_idandowner.weapondon’t refer to the new copy yet. Usecopy. -
The owner’s
^iand^dattributes are not available yet, because copy initializers run before them.
this is not bound inside the block. Use owner.
Dice Notation
damage: ^r:2d6+3 %% Roll 2 six-sided dice, add 3 treasure: ^r:d100 %% Roll 1 hundred-sided die healing: ^r:1d4+1 %% Roll 1 four-sided die, add 1
Probability Table
loot_type: |:common 60 :uncommon 25 :rare 10 :legendary 5| encounter: |#goblin 40 #orc 30 #troll 20 #dragon 10| weather: |"sunny" 50 "cloudy" 30 "rainy" 15 "stormy" 5|
Script Types
Event Script (arrow function, receives object and event)
on_use: (item, event) => {
player.health += item.healing_power;
return RezEvent.flash("You feel better!");
}
on_enter: (scene, event) => {
scene.visit_count = (scene.visit_count || 0) + 1;
return RezEvent.render();
}
Action Script (regular function, this is the owner object)
attack: function(target) {
const damage = this.attack_power + rollDie(6);
target.health -= damage;
return damage;
}
canAfford: function(price) {
return this.gold >= price;
}
Behavior Tree
behaviours: ^[
$select
[$sequence
[health_low]
[has_potion]
[use_potion]]
[$sequence
[enemy_nearby]
[attack_enemy]]
[wander_around]
]
Special Attributes
System Attributes (control Rez behavior)
$global: true %% Create global variable
$template: true %% Mark as template for copying
$js_ctor: "CustomClass" %% Use different JavaScript constructor
$built_in: true %% Mark as built-in (documentation only)
$no_archive: #{:scratch} %% Attributes to leave out of saved games
ID Suffix Attributes (automatic element references)
Rez implements a built in behaviour when it sees an attribute whose name has
the _id suffix. This suffix declares the attribute to be a reference to an
element with the corresponding id.
@actor player {
nemesis_id: #villain_1
}
This declares that the nemesis_id attribute has the value #villain_1 however,
during initialization, Rez will also add a nemesis attribute to the player
element which will be a reference to the villain_1 element.
@actor villian_1 {
name: "Suruman of Many Colours"
}
@card c_player_nemesis {
bindings: [
player: #player
]
content: ```
<p>Your current nemesis is ${player.nemesis.name}.</p>
```
}
You may, later, assign a new id to the nemesis_id attribute to update the
reference or assign an element reference to the nemesis attribute.
@actor villain_2 {
name: "Sauron"
}
@actor player {
on_return_of_the_king: (player) => {
// These two lines are equivalent
player.nemesis_id = "villain_2";
player.nemesis = $("villain_2");
}
}
In the background, all references to the nemesis attribute transparently look
up the value of the related nemesis_id attribute, and then the Javascript
reference for the element with that id.
If nemesis_id is set to an invalid id value references to the nemesis
property will raise an exception. Likewise setting the nemsis attribute to
a Javascript object without an id attribute will raise an exception. Note
that you should only assign references to elements to such properties.
Assigning an object that happens to have an id property will work but later
cause undefined errors.
Miscellaneous Topics
Including custom Javascript
To include a custom Javascript file into your game add the .js file to your assets folder and a corresponding @asset element to your game. Use the $js_runtime attribute to tell Rez that it should be included in the runtime.js file.
@asset custom_js {
file_name: "custom.js"
$js_runtime: true
}
To have a Javascript file included as a separate file, included before runtime.js, use $pre_runtime: true.
To apply the defer attribute to the corresponding <script> tag use $js_defer: true.
Using @object
Rez defines a number of generally useful elements like @actor, @item, @inventory, @scene and so forth. These elements have built-in behaviours designed to be useful but flexible.
However, there may be concepts in your game which don’t map to those predefined categories,
for example "classes" in an RPG. There are so many possible ways to have a class work in a game that Rez cannot really offer a useful starting point. For this type of situation there is @object.
The @object element allows you to create a fully-custom object that has no built-in behaviours (beyond what you get from the basic_object runtime prototype that all in-game objects share).
Let’s look at an example:
@object soldier {
specialisation: :combat
perk_ids: #{#two_weapon_style #pounce #shield_bash #second_wind}
}
@object two_weapon_style {
level: 3
label: "Fight with two weapons almost as well as one"
}
@object pounce {
level: 5
label: "Close distance to an enemy and engage them quicker"
}
@object shield_bash {
level: 7
label: "Shields can be a weapon in the right hands"
}
@object second_wind {
level: 9
label: "When the chips are down, you come out fighting"
}
@object wizard {
specialisation: :magic
perk_ids: #{#fast_cast #mana_surge #concentration #max_damage}
}
@object fast_cast {
level: 3
label: "Faster than a speeding magic missile"
}
@object mana_surge {
level: 5
label: "You can always reach down for just one more spell"
}
@object concentration {
level: 7
label: "Nothing can distract you"
}
@object max_damage {
level: 9
label: "Your fireballs are the crispiest"
}
@actor thaugrim_the_wise {
%% Code dealing with this actor can lookup available perks from
%% the Wizards class object
class_id: #wizard
}
How an author chooses to use these elements in their game is up to them, there are many ways that class membership & perks could be applied to in-game situations. You’d write callbacks or behaviours that make use of them. These elements can be referenced by $(<id>), the same as other elements and implement the basic_object abstraction.
Using Decisions
RezDecision is an object that doesn’t have an element. You create one when you want code (or perhaps the player) to make a yes/no decision, and to say why if the answer is no. Rez uses them itself: for example inventory methods such as add() return a decision, and an actor’s on_accept_item handler receives one to answer.
You can use a decision like this:
const decision = new RezDecision("Include adult themes", {info: "Toggle this on to include themes of sex & violence that might not be suitable for all. Leave it off for a family friendly experience."});
decision.defaultNo();
some_function_making_the_decision(decision);
if(decision.wasYes) {
// do something
} else {
console.log(`No, because: ${decision.reason}`);
}
The first argument describes what the decision is for (it’s available as decision.purpose). The optional second argument is a data object, see below.
some_function_making_the_decision(decision) is expected to call either decision.yes() or decision.no("reason"). If it calls neither, the decision stays as defaultNo() left it: no. If we had used decision.defaultYes() it would work the other way around. decision.usedDefault tells you whether the answer is still the default, and defaultNo() can be given a reason too.
A decision that nothing has answered, not even a default, is no, and decision.wasMade is false.
To read the answer use decision.result (or wasYes), which is true for yes, or wasNo. These are properties, not methods. decision.reason is the reason given for a no, and decision.explain() gives a description of the whole outcome, useful when debugging.
yes(), no(), defaultYes(), defaultNo(), and setData() all return the decision, so calls can be chained:
return decision.no("too heavy").setData("failed_on", "weight");
RezDecision also supports decision.hide(), which is "no, and don’t even mention it". For example we may have a door which could be locked but also hidden: hide (the player doesn’t know about it yet), no (the door is locked), yes (the door has been unlocked). decision.isHidden is true after hide().
You can pass data into a decision either through the second argument to new RezDecision() or with decision.setData(key, value), and decision.yes({key: value}) sets data too. Whoever receives the decision reads a value with decision.getData(key), which also takes a default to return if the key isn’t set (decision.getData("failed_on", "unknown")), or gets the whole data object from the decision.data property. This way the code making the decision can pass other information back along with it.
Using your own prototypes
The bult in Rez prototype objects are pretty flexible but you may want to replace one of them with your own object. You can do this using the $js_ctor attribute on any object.
@actor kaspar_gutman {
$js_ctor: "Gutman"
name: "Kaspar Gutman"
villain: true
end
Now, instead of using the RezActor() constructor function the initialization code will look for a Gutman() constructor function. Constructor functions are passed the id (in this case kaspar_gutman) and a map of attributes.
It is advisable to base your object on the object you are replacing.
Procedural Generation
Procedural generation is about content that is created at run-time and Rez has good support for this through it’s addCopy(), copyAssigningId() and copyWithAutoId() methods in basic_object.
Rez supports the idea that you will create 'template' elements that are designed to be copied and modified to create something new. You do this by applying the $template attribute to it and then calling the appropriate copy method.
Although most objects support copying, by specifying $template: true you will suppress some of Rez’s automatic initialization. This means that the copy will get its own initialization.
@actor T_npc {
$template: true
...
}
$("T_npc").addCopy();
addCopy() takes an optional options object: {id, post_init_fn}. id assigns a specific id to the copy (one is auto-generated if omitted). post_init_fn(copy) is called with the new copy after init() has completed — so on_init has already fired and every attribute has its normal accessor property, meaning plain copy.attrName = value assignment works as expected — but before the copy event fires. This makes post_init_fn the place to set instance-specific values that depend on information only the caller has, which an on_copy handler can then use to finish setting the object up.
For example, a monster template whose level should be driven by the current dungeon depth rather than a fixed range:
@actor T_monster {
$template: true
min_level: 1
max_level: 5
level: 1
on_copy: (npc, evt) => {
npc.assign_base_scores();
for(let i = 0; i < npc.level; i += 1) {
npc.level_up();
}
}
}
function generate_monster_for_level(dungeon_level) {
return $("T_monster").addCopy({
post_init_fn: (copy) => {
copy.min_level = Math.max(1, dungeon_level - 1);
copy.max_level = dungeon_level + 2;
copy.level = Math.rand_int_between(copy.min_level, copy.max_level);
}
});
}
Here post_init_fn overrides level (and, for consistency, min_level/max_level) with a value derived from dungeon_level before on_copy runs assign_base_scores() and the level-up loop, so the monster’s stats reflect the dungeon-level-driven range rather than the template’s static defaults. Monsters created directly ($("T_monster").addCopy(), no post_init_fn) still get sensible behaviour from on_copy using the template’s static level.
Best Practices and Patterns
Project Organization
Structure larger projects with clear separation:
src/
├── game.rez # Main game definition
├── characters/
│ ├── player.rez # Player character
│ ├── npcs.rez # Non-player characters
│ └── monsters.rez # Enemy creatures
├── locations/
│ ├── town.rez # Town scenes and cards
│ ├── dungeon.rez # Dungeon areas
│ └── overworld.rez # World map
├── items/
│ ├── weapons.rez # Weapon definitions
│ ├── armor.rez # Armor and protection
│ └── consumables.rez # Potions, scrolls, etc.
└── systems/
├── combat.rez # Combat mechanics
├── inventory.rez # Inventory management
└── dialogue.rez # Conversation system
Use the include macro to combine files:
%% In game.rez
@game {
name: "My Adventure"
%% ... game definition
}
%(characters/player.rez)
%(characters/npcs.rez)
%(locations/town.rez)
%(items/weapons.rez)
%(systems/combat.rez)
Naming Conventions
Use consistent naming patterns:
%% Scenes: describe location or context @scene forest_entrance @scene combat_arena @scene character_creation %% Cards: describe content or action @card explore_clearing @card merchant_dialogue @card level_up_screen %% Actors: role or name @actor village_guard @actor evil_wizard @actor shop_keeper %% Items: descriptive names @item rusty_sword @item healing_potion @item magic_amulet
State Management
Keep game state organized and predictable:
@game {
name: "Adventure Game"
%% Global game state
current_chapter: 1
player_score: 0
game_flags: {}
%% Helper methods for state
setFlag: function(name, value = true) {
this.modifyAttribute("game_flags", (flags) => { flags[name] = value; });
}
getFlag: function(name) {
return this.game_flags[name] || false;
}
addScore: function(points) {
this.player_score += points;
if (this.player_score >= 1000) {
this.setFlag("high_score_achieved");
}
}
}
player_score += points assigns the attribute, so Rez knows it has changed. setFlag sets a key inside
the game_flags record, which Rez cannot see, so it uses modifyAttribute to have the change saved.
See Changing Collections in Place for why this matters.
Error Handling
Handle edge cases gracefully:
@card examine_item {
bindings: [
target_item: () => {
const itemId = $("game").selected_item_id;
return itemId ? $(itemId) : null;
}
]
content: ```
$if(target_item) -> {%
<h3>${target_item.name}</h3>
<p>${target_item.description}</p>
<button event="use_item">Use Item</button>
%}
() -> {%
<p>No item selected to examine.</p>
<button card="inventory">Back to Inventory</button>
%}
```
}
Performance Tips
-
Use Global Sparingly: Only mark frequently-accessed objects as global. Every global is added to the bindings of every template and expression
-
Optimize Templates: Avoid complex calculations in template expressions
-
Choose the Right Dynamic Type: Match the attribute type to your use case
-
Cache Expensive Operations: Store calculated values rather than recalculating
-
Batch DOM Updates: Use
{render: true}to refresh all content at once
Choosing Between Dynamic Types:
%% Use ^p{} for values that change frequently and need to be current
health_percentage: ^p{return this.health * 100 / this.max_health;}
%% Use ^i{} for complex setup that rarely changes
starting_equipment: ^i{
return this.character_class === "warrior"
? ["sword", "shield", "armor"]
: ["dagger", "lockpicks", "cloak"];
}
%% Use regular attributes for values that change manually
experience: 0 %% Updated by events, not calculated
%% Use ^i{} with manual updates for expensive calculations
threat_level: ^i{return this.calculateThreatLevel();}
recalculate_threat: function() {
this.threat_level = this.calculateThreatLevel();
}
Template Optimization:
%% Good: use dynamic properties to move calculations out of templates
@actor player {
base_attack: 10
strength: 15
attack_power: ^p{return this.base_attack + Math.floor(this.strength / 2);}
}
content: ```
Attack Power: ${player.attack_power}
```
%% Less good: calculate every time template renders
content: ```
Attack Power: ${player.base_attack + Math.floor(player.strength / 2)}
```