let canvas, ctx, requestId;
let gameObjects = [];
let board;
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class Vector2D {
constructor(velocityX, velocityY) {
this.vX = velocityX;
this.vY = velocityY;
}
}
class GameObject {
constructor(spriteName, startPoint, velocity, bounceSound, shootSound) {
this.spriteImage = new Image();
this.spriteImage.src = spriteName;
this.currentPoint = startPoint;
this.velocity = velocity;
this.bounceSound = bounceSound;
this.shootSound = shootSound;
this.firinDelay = 2; //seconds
this.active = true;
};
Draw(ctx) {
ctx.drawImage(this.spriteImage, this.currentPoint.x, this.currentPoint.y);
};
Update() {
this.currentPoint.y += this.velocity.vY;
this.currentPoint.x += this.velocity.vX;
if ((this.currentPoint.x > 400 - this.spriteImage.width) || (this.currentPoint.x < 0)) {
this.velocity.vX = -this.velocity.vX;
}
if ((this.currentPoint.y > 400 - this.spriteImage.height) || (this.currentPoint.y < 0)) {
this.velocity.vY = -this.velocity.vY;
}
};
}
class TeddyBear extends GameObject {
constructor(startPoint, velocity, bounceSound, shootSound) {
super("teddybear.png", startPoint, velocity, bounceSound, shootSound);
};
}
class Board {
constructor(rows, cols) {
this.rows = rows;
this.cols = cols;
this.labirinth = [];
for (let i = 0; i < rows; i++) {
this.labirinth[i] = new Array(cols);
for (let j = 0; j < cols; j++) {
this.labirinth[i][j] = Math.random() * 100;
}
}
}
draw(context) {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
context.beginPath();
context.lineWidth = 1;
context.strokeStyle = "black";
if (i < j) {
context.fillStyle = "yellow";
} else {
context.fillStyle = "red";
}
context.rect(i * 40, j * 40, 40, 40);
context.fill();
context.stroke();
}
}
}
}
function init() {
// This function is called after the page is loaded
// Get the canvas
canvas = document.getElementById('myCanvas');
// Get the context
ctx = canvas.getContext('2d');
// Init gameTime
//gameTime = 0;
board = new Board(10, 10);
board.draw(ctx);
gameObjects.push(new TeddyBear(new Point(10, 10), new Vector2D(1, 3), null, null));
gameObjects.push(new TeddyBear(new Point(70, 70), new Vector2D(-1, -2), null, null));
}
function animationLoop(timestamp) {
// 1 - Clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 2 - Draw
for (let gameObject of gameObjects) {
gameObject.Draw(ctx);
gameObject.Update();
}
// 3 - Check collision
// call again mainloop after 16.6 ms (60 frames/s)
requestId = requestAnimationFrame(animationLoop);
}
function start() {
// Start the animation loop, targets 60 frames/s
requestId = requestAnimationFrame(animationLoop);
}
function stop() {
if (requestId) {
cancelAnimationFrame(requestId);
}
}
Comments