Published
Edited
Nov 26, 2019
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
mutable paddleX = w/2 - paddleLength/2; // paddleX should be mutable by mouse, initialized at the middle
Insert cell
// add a mouse event listener in another cell
mousemove = c.canvas.onmousemove = e => {
// https://www.w3schools.com/jsref/event_onmousemove.asp
// debugger;// try to inspect e and e.offsetX value
// https://www.w3schools.com/jsref/event_offsetx.asp
// use mouse control the most left of the paddle
// mutable paddleX = ( e.offsetX < w - paddleLength ) ? e.offsetX : w - paddleLength
// use mouse control the middle point of the paddle
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 = ({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 (true) {
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};
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 ( x < r ) c.fillText(`x < r : ${x < r}`, x + 20, (y < h/2)? y + 20 : y - 20);
if ( x + r > w ) c.fillText(`x + r > w : ${x + r > w}`, x - 120 , (y < h/2)? y + 20 : y - 20);
if ( y < r ) c.fillText(`y < r : ${y < r}`, ( x < w/2) ? x + 20 : x - 80, y + 20, );
if ( y + r > h ) c.fillText(`y + r > h : ${y + r > h}`,( x < w/2) ? x + 20 : x - 80, y - 20);
// draw the paddle
c.fillStyle = "blue";
c.fillRect(mutable paddleX,
h - scale, // paddleY
paddleLength, // width of the paddle
scale); // height of the paddle
// draw paddle starting point
c.fillStyle = "cyan";
c.fillRect(mutable paddleX, h - scale, 2, 2)
}
Insert cell
videoyt("Aznz6oLbuFQ")
Insert cell
import {videoyt, slider} 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