JSFiddle - React, Tailwind, and code Playground
by openHPI
HTML
<canvas id="playground" playgroundWidth="720" height="500"></canvas>
<div>
<label for="score_player1">Player 1</label>
<input type="number" value="0" id="score_player1" />
</div>
<div>
<label for="score_player2">Player 2</label>
<input type="number" value="0" id="score_player2" />
</div>
CSS
#playground {
border: 1px solid black;
}
JavaScript
// Ein Ball-Objekt wird definiert
function Ball(context) {
this.context = context
this.radius = 10
this.init()
}
// Der Ball wird an seine Ausgangsposition gesetzt
// Über das prototype Konstrukt können Objekten Methoden zugeordnet werden
Ball.prototype.init = function () {
this.x = this.context.width / 2
this.y = this.context.height / 2
this.deltaX = 0
this.deltaY = 0
}
// Der Ball wird in Bewegung gesetzt
Ball.prototype.start = function () {
this.deltaX = 2 * (Math.random() < 0.5 ? -1 : 1)
this.deltaY = 4 * (Math.random() < 0.5 ? -1 : 1)
}
// Die linke Begrenzung des Balles errechnet sich aus
// seiner x-Position (bezieht sich auf den Mittelpunkt)
// + der aktuellen Bewegung in x-Richtung
// - seinem Radius
Ball.prototype.getLeftBoundary = function () {
return this.x + this.deltaX - this.radius
}
// Die untere Begrenzung des Balles
Ball.prototype.getBottomBoundary = function () {
return this.y + this.deltaY + this.radius
}
// Die rechte Begrenzung des Balles
Ball.prototype.getRightBoundary = function () {
return this.x + this.deltaX + this.radius
}
// Die obere Begrenzung des Balles
Ball.prototype.getTopBoundary = function () {
return this.y + this.deltaY - this.radius
}
// Die x-Richtung des Balles wird umgekehrt
Ball.prototype.switchDirectionX = function () {
this.deltaX = -this.deltaX
}
// Die y-Richtung des Balles wird umgekehrt
Ball.prototype.switchDirectionY = function () {
this.deltaY = -this.deltaY
}
// Die Bewegung des Balles
Ball.prototype.move = function () {
this.x += this.deltaX
this.y += this.deltaY
}
// Der Ball wird gezeichnet
Ball.prototype.draw = function () {
this.context.ctx.beginPath()
this.context.ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true)
this.context.ctx.closePath()
this.context.ctx.fill()
}
// Ein Kollisions-Objekt wird definiert
function Collision(context, ball, player1, player2) {
this.context = context
this.ball = ball
...