A game of Pong written in JavaScript 🏓

preview_player
Показать описание
#JavaScript #Pong #game

JavaScript beginners pong game tutorial example explained
Рекомендации по теме
Комментарии
Автор

UPDATED (initial ball Y direction is more randomized)

const gameBoard =
const ctx = gameBoard.getContext("2d");
const scoreText =
const resetBtn =
const gameWidth = gameBoard.width;
const gameHeight = gameBoard.height;
const boardBackground = "forestgreen";
const paddle1Color = "lightblue";
const paddle2Color = "red";
const paddleBorder = "black";
const ballColor = "yellow";
const ballBorderColor = "black";
const ballRadius = 12.5;
const paddleSpeed = 50;
let intervalID;
let ballSpeed;
let ballX = gameWidth / 2;
let ballY = gameHeight / 2;
let ballXDirection = 0;
let ballYDirection = 0;
let player1Score = 0;
let player2Score = 0;
let paddle1 = {
width: 25,
height: 100,
x: 0,
y: 0
};
let paddle2 = {
width: 25,
height: 100,
x: gameWidth - 25,
y: gameHeight - 100
};

window.addEventListener("keydown", changeDirection);
resetBtn.addEventListener("click", resetGame);

gameStart();

function gameStart(){
createBall();
nextTick();
};
function nextTick(){
intervalID = setTimeout(() => {
clearBoard();
drawPaddles();
moveBall();
drawBall(ballX, ballY);
checkCollision();
nextTick();
}, 10)
};
function clearBoard(){
ctx.fillStyle = boardBackground;
ctx.fillRect(0, 0, gameWidth, gameHeight);
};
function drawPaddles(){
ctx.strokeStyle = paddleBorder;

ctx.fillStyle = paddle1Color;
ctx.fillRect(paddle1.x, paddle1.y, paddle1.width, paddle1.height);
ctx.strokeRect(paddle1.x, paddle1.y, paddle1.width, paddle1.height);

ctx.fillStyle = paddle2Color;
ctx.fillRect(paddle2.x, paddle2.y, paddle2.width, paddle2.height);
ctx.strokeRect(paddle2.x, paddle2.y, paddle2.width, paddle2.height);
};
function createBall(){
ballSpeed = 1;
if(Math.round(Math.random()) == 1){
ballXDirection = 1;
}
else{
ballXDirection = -1;
}
if(Math.round(Math.random()) == 1){
ballYDirection = Math.random() * 1; //more random directions
}
else{
ballYDirection = Math.random() * -1; //more random directions
}
ballX = gameWidth / 2;
ballY = gameHeight / 2;
drawBall(ballX, ballY);
};
function moveBall(){
ballX += (ballSpeed * ballXDirection);
ballY += (ballSpeed * ballYDirection);
};
function drawBall(ballX, ballY){
ctx.fillStyle = ballColor;
ctx.strokeStyle = ballBorderColor;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(ballX, ballY, ballRadius, 0, 2 * Math.PI);
ctx.stroke();
ctx.fill();
};
function checkCollision(){
if(ballY <= 0 + ballRadius){
ballYDirection *= -1;
}
if(ballY >= gameHeight - ballRadius){
ballYDirection *= -1;
}
if(ballX <= 0){
player2Score+=1;
updateScore();
createBall();
return;
}
if(ballX >= gameWidth){
player1Score+=1;
updateScore();
createBall();
return;
}
if(ballX <= (paddle1.x + paddle1.width + ballRadius)){
if(ballY > paddle1.y && ballY < paddle1.y + paddle1.height){
ballX = (paddle1.x + paddle1.width) + ballRadius; // if ball gets stuck
ballXDirection *= -1;
ballSpeed += 1;
}
}
if(ballX >= (paddle2.x - ballRadius)){
if(ballY > paddle2.y && ballY < paddle2.y + paddle2.height){
ballX = paddle2.x - ballRadius; // if ball gets stuck
ballXDirection *= -1;
ballSpeed += 1;
}
}
};
function changeDirection(event){
const keyPressed = event.keyCode;
const paddle1Up = 87;
const paddle1Down = 83;
const paddle2Up = 38;
const paddle2Down = 40;

switch(keyPressed){
case(paddle1Up):
if(paddle1.y > 0){
paddle1.y -= paddleSpeed;
}
break;
case(paddle1Down):
if(paddle1.y < gameHeight - paddle1.height){
paddle1.y += paddleSpeed;
}
break;
case(paddle2Up):
if(paddle2.y > 0){
paddle2.y -= paddleSpeed;
}
break;
case(paddle2Down):
if(paddle2.y < gameHeight - paddle2.height){
paddle2.y += paddleSpeed;
}
break;
}
};
function updateScore(){
scoreText.textContent = `${player1Score} : ${player2Score}`;
};
function resetGame(){
player1Score = 0;
player2Score = 0;
paddle1 = {
width: 25,
height: 100,
x: 0,
y: 0
};
paddle2 = {
width: 25,
height: 100,
x: gameWidth - 25,
y: gameHeight - 100
};
ballSpeed = 1;
ballX = 0;
ballY = 0;
ballXDirection = 0;
ballYDirection = 0;
updateScore();
clearInterval(intervalID);
gameStart();
};

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="gameContainer">
<canvas id="gameBoard" width="500" height="500"></canvas>
<div id="scoreText">0 : 0</div>
<button id="resetBtn">Reset</button>
</div>
<script src="index.js"></script>
</body>
</html>

#gameContainer{
text-align: center;
}
#gameBoard{
border: 3px solid;
}
#scoreText{
font-family: "consolas", monospace;
font-size: 100px;
}
#resetBtn{
font-family: "Permanent Marker", cursive;
font-size: 22px;
width: 100px;
height: 50px;
border: 4px solid;
border-radius: 15px;
cursor: pointer;
}

BroCodez
Автор

Hey bro!
I'm from Brazil and I don't have money to learn here....
With you I learn English and to program.
Thank you from the heart.
God bless you

brianxuan
Автор

IT was a wonderful experience to go through this set of 90 videos for JS, learned a lot, I salute you code bro!

kristijanlazarev
Автор

A nice way to learn some of the beginner stuff, and the way you coded it was really clean.

puppergump
Автор

underrated channel, very fast and daily uploading of a very useful content. thank you so much this is absolutely helpful to me while I am currently learning js

mushitoad
Автор

You have 420 thousand subs rn. Congratulations! Keep up the good content Bro. You are one of the best tutors on Youtube.

eminkilicaslan
Автор

Thank so much, best javascript course EVER!!!! thankyou so much Bro, Gog Bless you

rinadem
Автор

You have domenstrated game development briefly i cant thank you enough❤️

abodyzizo
Автор

I hope ur viewers came back man
I love ur vids ty for everything u've done
Much love bro ❤

nopaln
Автор

Luckily I started in your java tutorial series when I discovered your channel, javascript has a lot of common format for the syntax. I'm also studying your DS&A tutorial series, and that one is heavily related to both of these two languages that I am learning as well.

Hopefully I will finish that DS&A too so that I can go over c# and c++ programming.

marxLz
Автор

This is the channel we all needed but don't deserve. <3

redheadrusskie
Автор

Just now i knew that I can build a whole website with just a short html code and a huge js code. This content is perfect 👌 keep on it

yaqk_here
Автор

I am old enough to remember when Pong was the big new thing, so this was an especially fun one to try.

jabberdoggy
Автор

Keep up the good work. I really appreciate your content. This copywork and trying to understand it is the best way for me to learn as fast as possible.

dc.vrds
Автор

you literally upload the best programming content on youtube

ketle
Автор

Please make more cool games with Java too 🙏🙏

ahsan.nsafvan.n
Автор

Javascript Looks like a Great Coding Language!
Gonna learn it after C++.
Thanks again for Uploading Quality Coding Videos <3

overkil
Автор

In such a nerdy industry its great to have a chad among us

doJLife
Автор

Would be nice to get Bro video about Java Springboot tutorial...

vstad
Автор

Can you please do some tutorials on c# advanced topics like control and connecting to database please? I am a biggest fan i have seen all your videos about swing and now am pro on swing thanks to you bro ✌️✌️

michaelanteneh
join shbcf.ru