114 lines
2.3 KiB
HTML
114 lines
2.3 KiB
HTML
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
|
|
|
<style>
|
|
canvas {
|
|
border:1px solid #d3d3d3;
|
|
background-color: #333333;
|
|
}
|
|
</style>
|
|
|
|
</head>
|
|
<body onload="startGame()">
|
|
|
|
<script>
|
|
// "use strict";
|
|
|
|
var player1;
|
|
var player2;
|
|
var ball;
|
|
|
|
function startGame() {
|
|
player1 = new component(15, 60, "white", 10, 100);
|
|
player2 = new component(15, 60, "white", 455, 100);
|
|
// ball = new component(10, 10, "white", 240, 125);
|
|
ball = new component(10, 10, "white", 40, 125);
|
|
myGameArea.start();
|
|
}
|
|
|
|
var myGameArea = {
|
|
keys: new Map(),
|
|
canvas : document.createElement("canvas"),
|
|
start : function() {
|
|
this.canvas.width = 480;
|
|
this.canvas.height = 270;
|
|
this.context = this.canvas.getContext("2d");
|
|
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
|
|
this.interval = setInterval(gameLoop, 20);
|
|
window.addEventListener('keydown', function (e) {
|
|
myGameArea.keys.set(e.key, true);
|
|
})
|
|
window.addEventListener('keyup', function (e) {
|
|
myGameArea.keys.set(e.key, false);
|
|
})
|
|
},
|
|
clear : function() {
|
|
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
|
}
|
|
}
|
|
|
|
function component(width, height, color, x, y) {
|
|
this.width = width;
|
|
this.height = height;
|
|
this.speedX = 0;
|
|
this.speedY = 0;
|
|
this.x = x;
|
|
this.y = y;
|
|
this.update = function() {
|
|
ctx = myGameArea.context;
|
|
ctx.fillStyle = color;
|
|
ctx.fillRect(this.x, this.y, this.width, this.height);
|
|
}
|
|
this.newPos = function() {
|
|
this.x += this.speedX;
|
|
this.y += this.speedY;
|
|
}
|
|
}
|
|
|
|
function gameLoop() {
|
|
playerMove();
|
|
draw();
|
|
}
|
|
|
|
function draw() {
|
|
myGameArea.clear();
|
|
player1.update();
|
|
player2.update();
|
|
ball.update();
|
|
}
|
|
|
|
function playerMove() {
|
|
player1.speedX = 0;
|
|
player1.speedY = 0;
|
|
if ( myGameArea.keys.get("a") )
|
|
{ player1.speedX += -1; }
|
|
if ( myGameArea.keys.get("d") )
|
|
{ player1.speedX += 1; }
|
|
if ( myGameArea.keys.get("w") )
|
|
{ player1.speedY += -1; }
|
|
if ( myGameArea.keys.get("s") )
|
|
{ player1.speedY += 1; }
|
|
player1.newPos();
|
|
|
|
player2.speedX = 0;
|
|
player2.speedY = 0;
|
|
if ( myGameArea.keys.get("ArrowLeft") )
|
|
{ player2.speedX += -1; }
|
|
if ( myGameArea.keys.get("ArrowRight") )
|
|
{ player2.speedX += 1; }
|
|
if ( myGameArea.keys.get("ArrowUp") )
|
|
{ player2.speedY += -1; }
|
|
if ( myGameArea.keys.get("ArrowDown") )
|
|
{ player2.speedY += 1; }
|
|
player2.newPos();
|
|
}
|
|
|
|
</script>
|
|
|
|
|
|
|
|
</body>
|
|
</html>
|