Ceci est une ancienne révision du document !
/BrickBreaker /assets /images ball.png /src Ball.js Game.js InputHandler.js main.js Paddle.js index.html
Ne pas oublier d'utiliser la propriété type=“module” dans la balise script lorsqu'on inclut le script JS principal !!!
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Brick Breaker</title> <style> #gameScreen { /* bordure du canvas */ border: 1px solid black; } img { /* rendre les images invisibles */ display: none; } </style> </head> <body> <!-- Canvas --> <canvas id="gameScreen" width="800" height="600"></canvas> <!-- Les images sont incluses au niveau du HTML mais --> <!-- elles sont cachées au niveau du CSS --> <img id="imgBall" src="assets/images/ball.png"> <!-- Inclure script principal en tant que module --> <script type="module" src="src/main.js"></script> </body> </html>
import Game from './Game.js'; let canvas = document.getElementById("gameScreen"); let context = canvas.getContext("2d"); let game = new Game(canvas.width, canvas.height); game.start(); let lastTime = 0; function gameLoop(timestamp) { let deltaTime = timestamp - lastTime; lastTime = timestamp; context.clearRect(0, 0, canvas.width, canvas.height); game.update(deltaTime); game.draw(context); requestAnimationFrame(gameLoop); } requestAnimationFrame(gameLoop);
import Paddle from "./Paddle"; import InputHandler from "./InputHandler.js"; import Ball from "./Ball.js"; export default class Game { constructor(gameWidth, gameHeight) { this.gameWidth = gameWidth; this.gameHeight = gameHeight; } start() { this.paddle = new Paddle(this); this.ball = new Ball(this); this.gameObjects = [ this.ball, this.paddle, ]; new InputHandler(this.paddle); } update(deltaTime) { // this.paddle.update(deltaTime); // this.ball.update(deltaTime); this.gameObjects.forEach(object => object.update(deltaTime)); } draw(context) { // this.paddle.draw(context); // this.ball.draw(context); this.gameObjects.forEach(object => object.draw(context)); } }
export default class Paddle { constructor(game) { this.gameWidth = game.gameWidth; this.gameHeight = game.gameHeight; this.width = 150; this.height = 30; this.maxSpeed = 7; this.speed = 0; this.position = { x: this.gameWidth / 2 - this.width / 2, y: this.gameHeight - this.height - 10, } } moveLeft() { this.speed = -this.maxSpeed; } moveRight() { this.speed = this.maxSpeed; } stop() { this.speed = 0; } update(deltaTime) { this.position.x += this.speed; if(this.position.x < 0) this.position.x = 0; if(this.position.x + this.width > this.gameWidth) this.position.x = this.gameWidth - this.width; } draw(context) { context.fillStyle = '#0ff'; context.fillRect(this.position.x, this.position.y, this.width, this.height); } }