let config = { type: Phaser.AUTO, width: 800, height: 600, scene: { preload: preload, create: create, update: update } }; let game = new Phaser.Game(config); let that; let shoot; let win; let graphics; let rect; let viruses = []; let target; let maxEnemies = 20; let enemiesCount = maxEnemies; let enemiesText; let colors = ['bleu', 'rouge', 'vert']; function preload() { that = this; this.load.audio('shoot', [ 'sound/shoot.ogg', 'sound/shoot.mp3' ]); this.load.audio('win', [ 'sound/win.ogg', 'sound/win.mp3' ]); this.load.image('target', 'img/target.png'); this.load.image('bleu', 'img/virus-bleu.png'); this.load.image('rouge', 'img/virus-rouge.png'); this.load.image('vert', 'img/virus-vert.png'); this.load.image('bg', 'img/bg.png'); } function killVirus(player, virus) { virus.visible = false; --enemiesCount; enemiesText.setText('virus restant : '+enemiesCount); if (enemiesCount === 0) { enemiesText.visible = false; that.add.text(200, 250, 'Bonne annnée 2021 !', { fontSize: '32px', fill: '#000' }); that.add.text(250, 300, 'Si possible, sans virus', { fontSize: '14px', fill: '#000' }); win.play(); } } function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } function create() { this.add.image(400, 300, 'bg'); shoot = this.sound.add('shoot'); win = this.sound.add('win'); enemiesText = this.add.text(16, 16, 'virus restant : '+maxEnemies, { fontSize: '32px', fill: '#000' }); graphics = this.add.graphics(); viruses = new Array(maxEnemies).fill(null).map( function() { let color = colors[Math.floor(Math.random() * colors.length)]; return that.add.image(getRandomInt(800), getRandomInt(600), color); } ); rect = Phaser.Geom.Rectangle.Clone(this.cameras.main); target = this.add.image(400, 300, 'target'); this.input.on('pointermove', function (pointer) { target.x = pointer.x; target.y = pointer.y; }); this.input.on('pointerdown', function (pointer) { let pointerX = pointer.x; let pointerY = pointer.y; shoot.play(); for (let i = 0; i < maxEnemies; i++) { let virus = viruses[i]; let virusX = virus.x; let virusY = virus.y; if ( virus.visible && pointerX >= virusX - 94 && pointerX <= virusX + 94 && pointerY >= virusY - 94 && pointerY <= virusY + 94 ) { killVirus(null, virus); break; } } }, this); } function update() { viruses.forEach(function (virus, i) { let direction = getRandomInt(4); let x = (1 + Math.random() * i); let y = (1 + Math.random() * i); switch (direction) { case 1: virus.x += x; virus.y += y; break; case 2: virus.x += x; virus.y -= y; break; case 3: virus.x -= x; virus.y += y; break; case 4: virus.x -= x; virus.y -= y; break; } }); Phaser.Actions.WrapInRectangle(viruses, rect, 72); }