Published
Edited
Nov 26, 2019
Insert cell
Insert cell
viewof c = {
var c = DOM.context2d(w, h);
c.canvas.value = c;
// c.canvas.style.cursor = "none";
return c.canvas;
}
Insert cell
viewof newGame = button("new game"); // create a button
Insert cell
mutable gameover = {
newGame; // click to restart the game, here to reset gameover to false
return false;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
mutable paddleX = w/2 - paddleLength/2;
Insert cell
mousemove = c.canvas.onmousemove = e => {
if ( paddleLength/2 <= e.offsetX && e.offsetX < w - paddleLength/2 ) {
mutable paddleX = e.offsetX - paddleLength/2
} else if ( paddleLength/2 > e.offsetX ) {
mutable paddleX = 0
} else {
mutable paddleX = w - paddleLength
}

}
Insert cell
mutable ball = {
newGame; // click the button to rerun this cell to restart the game
return {r: scale, x: 0, y: 0, xSpeed: speed, ySpeed: speed};
}
Insert cell
gameloop = {
let n = 0;
let {r, x, xSpeed, y, ySpeed} = mutable ball;
function pauseBall(duration){
mutable ball = {r, x, y, xSpeed, ySpeed}
return Promises.delay(duration, mutable ball)
}
while (!mutable gameover) { // when gameover is true, stop the loop
x = x + xSpeed;
y = y + ySpeed;

if (x < r) {
xSpeed = Math.abs(xSpeed);
yield pauseBall(0);

}
if (x + r > w) {
xSpeed = -Math.abs(xSpeed);
yield pauseBall(0);
}
if (y < r) {
ySpeed = Math.abs(ySpeed);
yield pauseBall(0);
}
if (y + r > h) {
ySpeed = -Math.abs(ySpeed);
yield pauseBall(0);
}
mutable ball = {r, x, y, xSpeed, ySpeed};
let px = mutable paddleX;
if (y + r > h - scale
&& x + r > px
&& x - r < px + paddleLength) {
yield pauseBall(0);

ySpeed = -ySpeed;
xSpeed = ((x - px) / paddleLength - 0.5) * Math.PI * speed;
}
if ( y + r > h ) {
mutable gameover = true;
yield pauseBall(3000);
}
yield true;
}
}
Insert cell
draw = {
gameloop;
c.fillStyle="black";
c.fillRect(0,0,w,h);
const {r, x, y} = mutable ball;
c.beginPath();
c.fillStyle = "red";
c.arc(x, y, r, 0, 2 * Math.PI);
c.fill();
c.fillStyle = "green"
c.font = "15px Arial"
if ( y + r > h ) c.fillText(`y + r > h : ${y + r > h} gameover: ${gameover}`, (x < w/2)? x + 20 : x - 170, y - 20);

c.fillStyle = "blue";
c.fillRect(mutable paddleX,
h - scale,
paddleLength,
scale);
c.fillStyle = "cyan";
c.fillRect(mutable paddleX, h - scale, 2, 2)
}
Insert cell
videoyt("Aznz6oLbuFQ")
Insert cell
import {videoyt, slider, button} from "@embracelife/tutorial-utilities"
Insert cell
FileAttachment("chart.svg").image()
Insert cell
FileAttachment("chart.png").image()
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