A game of Pong written in JavaScript 🏓

Поделиться
HTML-код
  • Опубликовано: 28 дек 2024

Комментарии • 163

  • @BroCodez
    @BroCodez  2 года назад +64

    UPDATED (initial ball Y direction is more randomized)
    *****************************************************
    const gameBoard = document.querySelector("#gameBoard");
    const ctx = gameBoard.getContext("2d");
    const scoreText = document.querySelector("#scoreText");
    const resetBtn = document.querySelector("#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 = gameHeight - ballRadius){
    ballYDirection *= -1;
    }
    if(ballX = gameWidth){
    player1Score+=1;
    updateScore();
    createBall();
    return;
    }
    if(ballX 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();
    };



    Document



    0 : 0
    Reset


    #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;
    }

    • @doubletrouble260
      @doubletrouble260 2 года назад +12

      I trullt adore how instead of using a github link to share a sourcecode you just copypasted whole script in a youtube comment :D
      nevertheless, thanks for a wonderful tutorial!

    • @vincekiangalicia2383
      @vincekiangalicia2383 2 года назад +2

      ❤️

    • @ahugetire9328
      @ahugetire9328 2 года назад +4

      Hey bro I love your channel I have started learning HTML from your 1 hour HTML course , I'm planning on learning CSS and Javascript from your channel after finishing HTML, after Javascipt I will learn Rust programming language, can you make a course on Rust as well ? It would be really great
      Love from Oman

    • @masternobody1896
      @masternobody1896 2 года назад +1

      lmao bro code when did you become gigachad

    • @bobsmith4729
      @bobsmith4729 2 года назад

      Olá, a nossa plataforma gostaria de o convidar a anunciar para nós e nós pagaremos pelo seu anúncio, por favor contacte-me se estiver interessado, obrigado"

  • @brianxuan611
    @brianxuan611 2 года назад +47

    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

  • @kristijanlazarev
    @kristijanlazarev Год назад +8

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

  • @puppergump4117
    @puppergump4117 2 года назад +15

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

  • @mushitoad
    @mushitoad 2 года назад +5

    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

    • @puppergump4117
      @puppergump4117 2 года назад +1

      Yeah and he's one of the few people that can explain in simple terms what code is doing. idk why others seem to stumble over their explanations

    • @mushitoad
      @mushitoad 2 года назад +1

      @@puppergump4117 so trueeee!!

  • @rinadem5219
    @rinadem5219 Год назад +1

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

  • @abodyzizo1737
    @abodyzizo1737 2 года назад +1

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

  • @d0c.0v3rd0s3
    @d0c.0v3rd0s3 2 года назад +2

    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.

  • @marxLz
    @marxLz 2 года назад +3

    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.

  • @eminkilicaslan8945
    @eminkilicaslan8945 2 года назад +2

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

  • @one111won
    @one111won Год назад +1

    freaking amazing series!

  • @doJLife
    @doJLife 2 года назад

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

  • @snigdharoy1938
    @snigdharoy1938 Год назад +1

    Thanks a lot for this valuable Video

  • @малосольные-окурки
    @малосольные-окурки 7 месяцев назад

    i got it to the end of the course. thank you very much!

  • @nopaln
    @nopaln 2 года назад +1

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

  • @redheadrusskie
    @redheadrusskie 2 года назад

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

  • @ketle2228
    @ketle2228 2 года назад

    you literally upload the best programming content on youtube

  • @iyedbaassou3257
    @iyedbaassou3257 2 года назад +1

    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

  • @overki1l
    @overki1l 2 года назад +3

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

  • @vstad1
    @vstad1 2 года назад +2

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

  • @lucabinder9829
    @lucabinder9829 2 года назад +1

    I made my pong game more like the original in black and white and it looks nice. Thanks for the tutorial Bro Code.

  • @ahsan.nsafvan.n1897
    @ahsan.nsafvan.n1897 2 года назад +2

    Please make more cool games with Java too 🙏🙏

  • @chifoomaster4528
    @chifoomaster4528 2 года назад

    this channel is so underrated

  • @LucasSouza-tc1wz
    @LucasSouza-tc1wz 2 года назад +16

    Hey man! I am a college student, and your tutorials have helped me immensely. Do you have a patreon, or a donation website for us to show our gratitude? I would like to pay you a cup of coffee (or a beer) lol. All this knowledge for free is just crazy! Thank you so much!

    • @abdi5120
      @abdi5120 2 года назад +3

      Ikr this dude is so good with his explaining

  • @bhavnishbhardwaj2275
    @bhavnishbhardwaj2275 2 года назад +1

    Your voice and content is dam good ❤️

  • @wolfstar6055
    @wolfstar6055 2 года назад

    Bro actually a legend.

  • @anandomia3161
    @anandomia3161 2 года назад +2

    Love your videos. Can you please make a playlist on React?

  • @alessa004w
    @alessa004w 2 года назад

    loving this content, simple yet effective way to explain. keep it up
    !

  • @knightofglory9718
    @knightofglory9718 2 года назад +2

    Hello bro! I love your channel and I learned a lot from you, and I want to ask you if you can make a PHP course.

  • @farizfadlir6697
    @farizfadlir6697 2 года назад +2

    Can you make a tutorial php & laravel please

  • @mr.unknown5307
    @mr.unknown5307 2 года назад +1

    Please make course on PyGame tutorial

  • @rafikhz62
    @rafikhz62 Год назад

    Thank you you are the best bro I hope you open a live stream to make allow us to talk with you

  • @manikandanm5567
    @manikandanm5567 2 года назад

    Excellent work

  • @theswagger78.
    @theswagger78. Год назад

    Thanks dude for this amazing playlist , keep it up 🔥🔥

  • @SportSync_official
    @SportSync_official 2 года назад +3

    heyy mate bro code is back!

  • @MASTER-ub5xd
    @MASTER-ub5xd 2 года назад +2

    Bro Can u do tutorial on JavaScript ES2022 .

  • @Redditstories-78
    @Redditstories-78 2 года назад

    You deserve so much more subs your videos is entertaining and educational at the same time keep doing the great job you are doing

  • @michaelanteneh2862
    @michaelanteneh2862 2 года назад +2

    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 ✌️✌️

  • @ShaliniSingh-mv3ie
    @ShaliniSingh-mv3ie 2 года назад +1

    Please make a video on class time table management system software only using Java

  • @wandstick501
    @wandstick501 2 года назад +2

    Hey bro is it possible you make a tutorial about programming phones with android studio after this JS course? (Thanks alot for coming back to youtube).

  • @datodiasamidze3681
    @datodiasamidze3681 2 года назад +1

    thanks, this is really helpfull for me, can you do same as this play list about react?

  • @jacokyle0160
    @jacokyle0160 2 года назад +2

    Hey Bro, I’m a big fan of your channel. I just graduated high school and I’m majoring in Computer Science next year. I want to spend the summer coding, but I don’t know where to begin.
    I’m essentially starting from scratch after taking a course in Python from Udacity. My main interests are working with data and math (I’ve taken multivariable calculus). I’m asking you because I enjoy your detailed content, and I know you’ll have a lot of experience answering these types of questions. I’m looking to learn robust skills and make cool projects and generally avoid being bored. Hope you can help. Thanks.

  • @danielmelek9348
    @danielmelek9348 2 года назад +1

    Thank you bro Code. Make a React video please

  • @apoorvsinghchouhan2033
    @apoorvsinghchouhan2033 2 года назад +1

    Sir, can you make a tutorial on Nodejs ?

  • @vegetaswag2467
    @vegetaswag2467 2 года назад +1

    Hey dude just asking r u gonna do any c# games and stuff like the rock paper scissors and guess the number ones because they were really fun to follow and learn! Keep the amazing work up!

  • @Grudi28
    @Grudi28 2 года назад

    What a legend, this is really cool

  • @Medigus
    @Medigus 2 года назад +1

    Can you make a Lua course?

  • @allantohaina1287
    @allantohaina1287 2 года назад

    please can you make a video about reflexion thanks and listener in other class

  • @MichelZelff
    @MichelZelff 2 года назад

    Can you make a django tutorial?! You are the best

  • @wikoroo2366
    @wikoroo2366 2 года назад

    Well, I gotta watch this one now.
    Btw, are there any chances of you making a Lua tutorial?

  • @moneylisa9848
    @moneylisa9848 2 года назад

    you are doing god's work

  • @irfanquader6417
    @irfanquader6417 2 года назад

    bro you are awesome

  • @bokasam1643
    @bokasam1643 2 года назад +5

    You are a legend !!!! and a big inspiration. You make coding super easy. Would love to know if you will be doing any content on WEB 3.0...A BIG THING!! Your great knowledge will really go a long way to help us understand all about solidity and building web3 dApps

  • @aaksadeeq
    @aaksadeeq 2 года назад

    Hey bro!
    Your are the best 💖

  • @shawwfr
    @shawwfr 2 года назад

    hi i have a suggtion for a video do you think you could make a video on how to make a extension for crome? (if you havint already)

  • @robinpage2730
    @robinpage2730 2 года назад

    Do Lua programming language as your next tutorial series!

  • @echobytehax
    @echobytehax 2 года назад +1

    bro please make tutorial c++ OOP

  • @Goldenknowledgeforyou
    @Goldenknowledgeforyou 2 года назад

    Bro helps me!!!!!
    How can I publish my HTML website on the internet?

  • @sandeepsonu7330
    @sandeepsonu7330 2 года назад

    Hello, Please make a video on data structures and algorithms in python

  • @towbeetowbee3124
    @towbeetowbee3124 2 года назад

    can u make a video about discrete math

  • @saimrudula2140
    @saimrudula2140 2 года назад

    Wow after a long time bro how are you doing

  • @Akas766
    @Akas766 2 года назад

    great bro. rust language video want

  • @Squeezyness
    @Squeezyness 2 года назад

    Could you make a tutorial series on Java Spring Boot? Pretty please with cherry on top?

  • @melkor1177
    @melkor1177 2 года назад +1

    Can you do ethical hacking/cyber security courses?

  • @a.m.a.b7368
    @a.m.a.b7368 2 года назад

    Would you please
    Give me a road map for learning programming the fastest and most *efficient way* ???

  • @ianhuang8613
    @ianhuang8613 2 года назад

    Hey Bro, please update the video as soon as possible, I am looking forward to it!!!🤩🤩🤩🤩

  • @pyrytheburger3869
    @pyrytheburger3869 2 года назад

    Can you make haxe full course?

  • @andrewschvab
    @andrewschvab 2 года назад +1

    9:50 idk why but it doesnt draw the paddle :( anyone can help me? i checked the code, everything checks out but it doesnt draw the paddle. only difference in my code is that i typed "black" instead of whatever colour he chose :(

    • @andrewschvab
      @andrewschvab 2 года назад

      console says "cannot rea properties on null" for gameBoard

  • @mohammadabuthaher4213
    @mohammadabuthaher4213 2 года назад

    You are amazing
    I watch your videos and they are helpful
    Now I have a project but I have some problems
    Can you help me with my project?

  • @vladlux4245
    @vladlux4245 2 года назад

    pov ur with a 60 percent keyboard

  • @dra_ger5534
    @dra_ger5534 2 года назад

    Hello Bro Code, can you make a video to talk about programming 2D games in python?

  • @Clowning.
    @Clowning. 2 года назад

    can you please make course about Lua i wanna learn that to make games in love :(

  • @samifly2753
    @samifly2753 Год назад

    How to increase and decrease the speed of the ball ?

  • @KKDKNGw8j
    @KKDKNGw8j 17 дней назад +1

    pls send the github link cuz my console is giving me a lot of errore with this one

    • @KKDKNGw8j
      @KKDKNGw8j 17 дней назад

      its working now but I can't control the blue paddle

  • @marxLz
    @marxLz 2 года назад

    Hello dude. I just wanma ask if the contents you have in this 90-video playlist is the same with the other playlist containing 60 videos. I just found both of the playlist when I'm looking for your tutorial on javascript.

  • @Shafiifiqh
    @Shafiifiqh 2 года назад

    Can you do rust please

  • @mintz347
    @mintz347 2 года назад

    Pls bro can you make video how to get your first job jr position

  • @ken3346
    @ken3346 2 года назад

    Bro can ya make a vid for LUA pls?

  • @rasyinggantv1717
    @rasyinggantv1717 2 года назад

    Bro pls make the typescript programming language tutorial, i need it

  • @atishkumarsahu6095
    @atishkumarsahu6095 Год назад

    @BroCodez bro could you please make a project on Sudoku Game In Web Development and in that project there will be different types of level and every new game there is a new game board where the numbers from 1 to 9 will be in random order in random section in every new game and there is a button whose name is solution and when you click on that button you can see the solution of that particular game and every new game the solution button will give the appropriate solution for that game.

  • @Yanto_Rundy96
    @Yanto_Rundy96 2 года назад

    Could you make program to calculate E=MC2?

  • @davoskyygot7
    @davoskyygot7 2 года назад +1

    Hey bro pls can you give us tut on php?

  • @jotarokujo9474
    @jotarokujo9474 2 года назад

    Hey bro! I want some advice.
    From u I have learned java and learning javascript but I am one of those guys who suffer from imposter syndrome. so what should I do? if I have to do some example projects can u give me ideas?
    BTW you make epic videos, keep it up, and best of luck :thumbsup: .

  • @onurguzel16
    @onurguzel16 2 года назад +1

    Hi Bro, why doesn't VS code offer code completetion while you're coding in Javascript and when you press dot?

  • @عمرعبدالرحيم-خ2ل
    @عمرعبدالرحيم-خ2ل 2 года назад

    make a ruby course please

  • @abdullahmuhtorzonov6941
    @abdullahmuhtorzonov6941 2 года назад +1

    hey bro can you create a game like a mario?

    • @user-ii5qx4vw3q
      @user-ii5qx4vw3q 2 года назад

      Definitely! Send a text on WhatsApp to the number displayed above. Let's work!!

  • @anoridinaryhumanbeing70
    @anoridinaryhumanbeing70 2 года назад +1

    How to become a pro coder at leetcode??

  • @abdulalimmahir
    @abdulalimmahir 2 года назад

    I don't know if you have time, but I request you to make videos on a few Scripting Language(Like : Lua, Squirrel etc).
    much ❤

  • @Quex-q6o
    @Quex-q6o 2 года назад

    the top, when I installed soft soft (restart didn't help). I have a creative softblaster z softcard. I'm assuming it has sotNice tutorialng to do

  • @ragexdad5059
    @ragexdad5059 2 года назад

    Lua next please

  • @МаксимМіщук-п2в
    @МаксимМіщук-п2в 2 года назад

    hi bro.Do django full course pls

  • @juanestebanparraparra8531
    @juanestebanparraparra8531 2 года назад

    Bro, you should do a Kotlin tutorial!!!!

  • @davronbekmukhtorov2556
    @davronbekmukhtorov2556 2 года назад

    BRO CAN YOU MAKE MORE VIDEOS IN JAVA ITSELF

  • @bane2aki832
    @bane2aki832 2 года назад

    For the youtube algorithm! 🙏🙏🙏

  • @kkumar5830
    @kkumar5830 2 года назад

    Bro java game builds plees

  • @thatoneocto
    @thatoneocto 2 года назад

    Can you teach rust?

  • @vinayaksingh524
    @vinayaksingh524 2 года назад +1

    Bro code in a few days:
    Re making an os in javascript
    Also next cpp video when :v

  • @robinpage2730
    @robinpage2730 2 года назад

    You must do Cobol. And Basic

  • @nbamol5453
    @nbamol5453 2 года назад

    anyones ball get stuck on checkCollision function?

  • @Nain9_Life
    @Nain9_Life 2 года назад

    Increíble