import AbstractView from './AbstractView.js' export default class extends AbstractView { constructor(params) { super(params, 'Game'); this.game = null; } async getHtml() { return `

Game

`; } async postInit() { document.getElementById('startGameButton').onclick = this.startGame; } startGame() { if (this.game == null) this.game = new Game; } } class Game { constructor() { this.canvas = document.createElement('canvas'); this.canvas.width = 480; this.canvas.height = 270; this.canvas.style.border = '1px solid #d3d3d3'; this.canvas.style.backgroundColor = '#f1f1f1'; this.context = this.canvas.getContext('2d'); this.paddle = new Paddle(this.context); document.getElementById('app').appendChild(this.canvas); this.interval = setInterval(this.updateGame.bind(this), 10); this.keys = []; document.addEventListener('keydown', this.keyDownHandler.bind(this)); document.addEventListener('keyup', this.keyUpHandler.bind(this)); } clear() { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } updateGame() { if (this.keys.includes('s')) this.paddle.y += 3; if (this.keys.includes('w')) this.paddle.y -= 3; this.clear(); this.paddle.update(); } keyUpHandler(ev) { const idx = this.keys.indexOf(ev.key); if (idx != -1) this.keys.splice(idx, 1); } keyDownHandler(ev) { if (this.keys.indexOf(ev.key) == -1) this.keys.push(ev.key); } } class Paddle { constructor(context) { this.width = 10; this.height = 70; this.x = 5; this.y = 100; this.ctx = context; this.update(); } update() { this.ctx.fillStyle = 'black'; this.ctx.fillRect(this.x, this.y, this.width, this.height); } }