Published
Edited
Nov 7, 2021
Insert cell
Insert cell
Insert cell
cnv = html`<canvas class="game" height="320" width="480"></canvas>`
Insert cell
k = Kaboom({
global: false,
width: 480,
height: 320,
canvas: cnv,
background: [0,0,256]
})
Insert cell
main = {
k.scene("main", ()=> {
k.add([
k.text("Press space to get funky", { width: k.width() }),
k.pos(12, 12),
]);

const bean = k.add([
k.sprite("bean"),
k.pos(k.center()),
k.origin("center"),
k.scale(1),
k.color(),
k.area(),
// Use our component here
funky(),
// Tags are empty components, it's equivalent to a { id: "friend" }
"friend",
// Plain objects here are components too and work the same way, except unamed
{
coolness: 100,
friends: [],
},
]);

k.onKeyPress("space", () => {
// .coolness is from our unamed component above
if (bean.coolness >= 100) {
// We can use .getFunky() provided by the funky() component now
bean.getFunky()
}
});
k.onKeyPress("r", () => {
// .use() is on every game object, it adds a component at runtime
bean.use(k.rotate(180))
});
})

k.go("main")
}
Insert cell
Kaboom = (await import('https://cdn.skypack.dev/kaboom@2000.1.0?min')).default
Insert cell
Insert cell
FileAttachment("heart.png").url()
Insert cell
// Components are just functions that returns an object that follows a certain format
function funky() {

// Can use local closed variables to store component state
let isFunky = false

return {

// ------------------
// Special properties that controls the behavior of the component (all optional)

// The name of the component
id: "funky",
// If this component depend on any other components
require: [ "scale", "color", ],

// Runs when the host object is added to the game
add() {
// E.g. Register some events from other components, do some bookkeeping, etc.
},

// Runs every frame as long as the host object exists
update() {

if (!isFunky) return

// "this" in all component methods refers to the host game object
// Here we're updating some properties provided by other components
this.color = k.rgb(k.rand(0, 255), k.rand(0, 255), k.rand(0, 255))
this.scale = k.rand(1, 2)

},

// Runs every frame (after update) as long as the host object exists
draw() {
// E.g. Custom drawXXX() operations.
},

// Runs when the host object is destroyed
destroy() {
// E.g. Clean up event handlers, etc.
},

// Get the info to present in inspect mode
inspect() {
return isFunky ? "on" : "off"
},

// ------------------
// All other properties and methods are directly assigned to the host object

getFunky() {
isFunky = true
},

}

}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more