xxxxxxxxxx
// object-oriented programming (OOP)
// is programming using OBJECTS
// objects are pieces of computer code
// that contain both functions *and* data
//
// objects in javascript are accessed through
// things called "classes"
// classes have methods which are functions
// classes have properties which are variables
// classes also have a constructor function which runs
// when you make one. this is called instantiation.
var NUMROWS = 5;
var NUMCOLUMNS = 10;
var BWIDTH = 40;
var BHEIGHT = 15;
var BHSPACING = 5;
var BVSPACING = 5;
var bricks = []; // array to hold all the bricks
var ball; // variable to contain a ball
function setup() {
createCanvas(windowWidth, windowHeight);
restartGame();
}
function draw() {
background(0);
for(let i = 0;i<bricks.length;i++)
{
bricks[i].draw();
}
ball.draw();
}
function keyTyped()
{
restartGame();
}
function restartGame() {
bricks = []; // reinitialize the bricks array
for(let i = 0;i<NUMROWS*NUMCOLUMNS;i++)
{
let c = i%NUMCOLUMNS;
let r = floor(i/NUMCOLUMNS);
bricks[i] = new Brick(c*(BWIDTH+BHSPACING), r*(BHEIGHT+BVSPACING), BWIDTH, BHEIGHT);
}
// make a new ball:
ball = new Ball();
}
// this is going to be a class definition for the bricks:
class Brick {
// constructor: runs when you instantiate the class ("new" on a object)
constructor(x=width/2,y=height/2,w=10,h=10)
{
// set some properties:
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.r = random(128,255);
this.g = random(128,255);
this.b = random(128,255);
}
// add some methods:
draw()
{
fill(this.r,this.g,this.b);
rect(this.x,this.y,this.w,this.h);
}
}
// this is going to be a class definition for the ball:
class Ball {
// constructor: runs when you instantiate the class ("new" on a object)
constructor(x=width/2,y=height*2/3,v=5,a=random(TWO_PI))
{
// set some properties:
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.velocity = v;
this.angle = a;
}
// add some methods:
draw()
{
fill(255);
ellipse(this.x,this.y,15,15);
this.px = this.x;
this.py = this.y;
this.x = this.x + this.velocity * cos(this.angle);
this.y = this.y + this.velocity * sin(this.angle);
// make the ball bounce off the walls:
if(this.x>width) this.angle = PI - this.angle;
if(this.x<0) this.angle = PI - this.angle;
if(this.y>height) this.angle = TWO_PI - this.angle;
if(this.y<0) this.angle = TWO_PI - this.angle;
}
}