A game of Snake written in JavaScript 🐍

แชร์
ฝัง
  • เผยแพร่เมื่อ 23 พ.ย. 2024

ความคิดเห็น • 110

  • @BroCodez
    @BroCodez  2 ปีที่แล้ว +86

    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 = "white";
    const snakeColor = "lightgreen";
    const snakeBorder = "black";
    const foodColor = "red";
    const unitSize = 25;
    let running = false;
    let xVelocity = unitSize;
    let yVelocity = 0;
    let foodX;
    let foodY;
    let score = 0;
    let snake = [
    {x:unitSize * 4, y:0},
    {x:unitSize * 3, y:0},
    {x:unitSize * 2, y:0},
    {x:unitSize, y:0},
    {x:0, y:0}
    ];
    window.addEventListener("keydown", changeDirection);
    resetBtn.addEventListener("click", resetGame);
    gameStart();
    function gameStart(){
    running= true;
    scoreText.textContent = score;
    createFood();
    drawFood();
    nextTick();
    };
    function nextTick(){
    if(running){
    setTimeout(()=>{
    clearBoard();
    drawFood();
    moveSnake();
    drawSnake();
    checkGameOver();
    nextTick();
    }, 75);
    }
    else{
    displayGameOver();
    }
    };
    function clearBoard(){
    ctx.fillStyle = boardBackground;
    ctx.fillRect(0, 0, gameWidth, gameHeight);
    };
    function createFood(){
    function randomFood(min, max){
    const randNum = Math.round((Math.random() * (max - min) + min) / unitSize) * unitSize;
    return randNum;
    }
    foodX = randomFood(0, gameWidth - unitSize);
    foodY = randomFood(0, gameWidth - unitSize);
    };
    function drawFood(){
    ctx.fillStyle = foodColor;
    ctx.fillRect(foodX, foodY, unitSize, unitSize);
    };
    function moveSnake(){
    const head = {x: snake[0].x + xVelocity,
    y: snake[0].y + yVelocity};

    snake.unshift(head);
    //if food is eaten
    if(snake[0].x == foodX && snake[0].y == foodY){
    score+=1;
    scoreText.textContent = score;
    createFood();
    }
    else{
    snake.pop();
    }
    };
    function drawSnake(){
    ctx.fillStyle = snakeColor;
    ctx.strokeStyle = snakeBorder;
    snake.forEach(snakePart => {
    ctx.fillRect(snakePart.x, snakePart.y, unitSize, unitSize);
    ctx.strokeRect(snakePart.x, snakePart.y, unitSize, unitSize);
    })
    };
    function changeDirection(event){
    const keyPressed = event.keyCode;
    const LEFT = 37;
    const UP = 38;
    const RIGHT = 39;
    const DOWN = 40;
    const goingUp = (yVelocity == -unitSize);
    const goingDown = (yVelocity == unitSize);
    const goingRight = (xVelocity == unitSize);
    const goingLeft = (xVelocity == -unitSize);
    switch(true){
    case(keyPressed == LEFT && !goingRight):
    xVelocity = -unitSize;
    yVelocity = 0;
    break;
    case(keyPressed == UP && !goingDown):
    xVelocity = 0;
    yVelocity = -unitSize;
    break;
    case(keyPressed == RIGHT && !goingLeft):
    xVelocity = unitSize;
    yVelocity = 0;
    break;
    case(keyPressed == DOWN && !goingUp):
    xVelocity = 0;
    yVelocity = unitSize;
    break;
    }
    };
    function checkGameOver(){
    switch(true){
    case (snake[0].x < 0):
    running = false;
    break;
    case (snake[0].x >= gameWidth):
    running = false;
    break;
    case (snake[0].y < 0):
    running = false;
    break;
    case (snake[0].y >= gameHeight):
    running = false;
    break;
    }
    for(let i = 1; i < snake.length; i+=1){
    if(snake[i].x == snake[0].x && snake[i].y == snake[0].y){
    running = false;
    }
    }
    };
    function displayGameOver(){
    ctx.font = "50px MV Boli";
    ctx.fillStyle = "black";
    ctx.textAlign = "center";
    ctx.fillText("GAME OVER!", gameWidth / 2, gameHeight / 2);
    running = false;
    };
    function resetGame(){
    score = 0;
    xVelocity = unitSize;
    yVelocity = 0;
    snake = [
    {x:unitSize * 4, y:0},
    {x:unitSize * 3, y:0},
    {x:unitSize * 2, y:0},
    {x:unitSize, y:0},
    {x:0, y:0}
    ];
    gameStart();
    };



    Document



    0
    Reset


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

    • @octobsession3061
      @octobsession3061 2 ปีที่แล้ว

      Madlad

    • @octobsession3061
      @octobsession3061 2 ปีที่แล้ว +1

      @@Kanjiidesu mayne you forgot to open your eyes

    • @manipurihunabopa
      @manipurihunabopa ปีที่แล้ว +1

      Hey, bro. You're an amazing teacher. I like that. Your codes are clean and really a child can understand it

    • @laverico
      @laverico ปีที่แล้ว

      ​@@Kanjiidesuif you just copied and paste the whole code in the comment in one file, then yeah it aint workin'

    • @KamalTiwari82
      @KamalTiwari82 ปีที่แล้ว

      @@lavericoyou have probably resolved this by now but if not check that css and us files are linked.

  • @vitordejesusferreira
    @vitordejesusferreira ปีที่แล้ว +3

    if you guys are having velocity change when click restart button,
    the solution its just delete de last , call function "*yourFunction()*".
    in the example of this video its the last 'gameStart()' call .

  • @mibrahim2001
    @mibrahim2001 2 ปีที่แล้ว +9

    If you guys are facing the increasing speed issue on clicking the reset button:
    What you can do is create a gobal variable for timeout and store setTimeout() in that variabe in the nextTick() function. Then in the reset function do this:
    clearTimeout(*your variable name*)

    • @syedyousuffaizan1779
      @syedyousuffaizan1779 ปีที่แล้ว

      can you please elaborate it more ?

    • @syedyousuffaizan1779
      @syedyousuffaizan1779 ปีที่แล้ว

      I tried making this variable in the nextTick() function
      var timeout = setTimeout(()=>{
      clearBoard()
      drawFood()
      movesnake()
      drawsnake()
      checkgameover()
      nextTick()
      }, 75)
      and called it again the resetGame() function as interTimeout(timeout). but it didnt work am i doing something wrong?
      you assistance would be really appriciated

    • @Amadtheus7
      @Amadtheus7 ปีที่แล้ว +1

      @@syedyousuffaizan1779 His method works, just create a global variable in the top of your code
      var timeout = setTimeout;
      and in the function nextTick, do this
      function nextTick(){
      if(running){
      timeout = setTimeout(()=> {
      clearBoard();
      drawFood();
      moveSnake();
      drawSnake();
      checkGameOver();
      nextTick();
      }, 100);
      }
      else{
      displayGameOver();
      }
      };
      and in the function resetGame, do this:
      function resetGame(){
      score = 0;
      xVelocity = unitSize;
      yVelocity = 0;
      snake = [
      {x:unitSize * 4, y:0},
      {x:unitSize * 3, y:0},
      {x:unitSize * 2, y:0},
      {x:unitSize, y:0},
      {x:0, y:0}
      ];
      clearTimeout(timeout);
      gameStart();
      };

    • @littlecurrybread
      @littlecurrybread 9 หลายเดือนก่อน

      this one works for me, for anyone having issues:
      If youre having issues with the increased speed on resetBtn, do this: new global variable somewhere before game_start();
      let time_out_id;
      then add this to your function next_tick. You can see time_out_id = setTimeOut below
      function next_tick(){
      if (running){
      time_out_id = setTimeout (()=>{
      clear_board();
      draw_food();
      move_snake();
      draw_snake();
      check_game_over();
      next_tick();
      }, 100);
      }
      else {
      display_game_over();
      }
      };
      LASTLY
      reset the setTimeout by using the id function we created in the reset function
      function reset_game(){
      score = 0;
      x_velocity = unit_size;
      y_velocity = 0;
      snake = [
      {x:unit_size * 4, y:0},
      {x: unit_size * 3, y:0},
      {x:unit_size * 2, y:0},
      {x:unit_size, y:0},
      {x: 0, y: 0}
      ];
      clearTimeout(time_out_id)
      game_start();
      };

  • @noir371
    @noir371 2 ปีที่แล้ว +12

    I like your style of programming. Super methodical, lay everything out then fill it in

  • @juandavidcastroarias7115
    @juandavidcastroarias7115 ปีที่แล้ว +3

    Congratulations, you are a master, i am learning with your JS course, i am from Colombia, thank you for your help.

  • @alejandrogarzonbello5285
    @alejandrogarzonbello5285 2 ปีที่แล้ว +6

    Hey i have noticed a little mistake in the code. If you want to use other dimensions ( a smaller number for heigth ) for the board when it generates new food is going to be invisible. This is because in the createFood method you assign to foodY the value of the gameWidth also. In your case it doesnt matter because the heigth and width are the same.

  • @iceman442ho
    @iceman442ho 2 ปีที่แล้ว +4

    Thanks, Bro. You don't know how much you just helped me.

  • @yasser7082
    @yasser7082 ปีที่แล้ว

    you can changing the code in the resetGame function to location.reload() and it's do the same thing

  • @littlecurrybread
    @littlecurrybread 9 หลายเดือนก่อน

    If youre having issues with the increased speed on resetBtn, do this: new global variable somewhere before game_start();
    let time_out_id;
    then add this to your function next_tick. You can see time_out_id = setTimeOut below
    function next_tick(){
    if (running){
    time_out_id = setTimeout (()=>{
    clear_board();
    draw_food();
    move_snake();
    draw_snake();
    check_game_over();
    next_tick();
    }, 100);
    }
    else {
    display_game_over();
    }
    };
    LASTLY
    reset the setTimeout by using the id function we created in the reset function
    function reset_game(){
    score = 0;
    x_velocity = unit_size;
    y_velocity = 0;
    snake = [
    {x:unit_size * 4, y:0},
    {x: unit_size * 3, y:0},
    {x:unit_size * 2, y:0},
    {x:unit_size, y:0},
    {x: 0, y: 0}
    ];
    clearTimeout(time_out_id)
    game_start();
    };

  • @hunin27
    @hunin27 11 หลายเดือนก่อน +1

    Hey, I have found a bug both in mine and in your snake game.
    When you move the direction, you immediately change it, but the snake moves only after a certain amount of time..
    This means that the if statement to check if it is not going right when moving left, will work. But i could change direction to up or down and before the moveSnake function gets called, change it back to left, since direction is up or down, moving left is allowed. and you die because you collide with your body...
    I have found two solutions, but they are not very good..
    1) Move the snake immediately when the user changes direction. It's bad because you could go very fast by switching direction at all times.
    2) Make the user change direction only after 200ms. It's bad because it makes the game very laggy and slow..
    Thanks bro. Lots of love from Cyprus ( I'm in vacation now :) )

    • @yousefjalali7246
      @yousefjalali7246 8 หลายเดือนก่อน

      I faced the same bug, the solution is to use a queue to store the events and execute them in order.

  • @daniellegeelen1302
    @daniellegeelen1302 26 วันที่ผ่านมา

    nice game :D Only when I made the game canvas wider, sometimes I didn't have an apple, as it was spawning outside of the canvas. As in the "createFood" function on the bottom at "foodY =..." it says ..."gameWidht..." instead of "...gameHeight..."
    function createFood(){
    function randomFood(min, max){
    const randNum = Math.round((Math.random() * (max - min) + min) / unitSize) * unitSize;
    return randNum;
    }
    foodX = randomFood(0, gameWidth - unitSize);
    foodY = randomFood(0, gameWidth - unitSize);

  • @krampuswinter5917
    @krampuswinter5917 2 ปีที่แล้ว +7

    Thanks a lot, great content!

  • @Kickthewall
    @Kickthewall 2 ปีที่แล้ว

    I’m currently studying python js and c# ur videos make it way easier to understand

  • @1huang649
    @1huang649 ปีที่แล้ว +1

    At the createFood function, why did he minus the min from max and plus min? I can't figure it out, the min is 0. What is the purpose of using min?

    • @k00lmoh
      @k00lmoh 6 หลายเดือนก่อน +1

      this is a standard way to get a random number between min and max, however in his case, it just happens that min is 0 thus using it (min) or removing it does the same, however if you try a minimum of (min = 5) the result will be a random number between 5 and max

  • @Trebuh2137
    @Trebuh2137 2 ปีที่แล้ว +3

    if you spam the reset button the snake gets very fast

    • @michaeld4337
      @michaeld4337 2 ปีที่แล้ว +2

      God revealed to me it's because BroCode didn't do clearInterval for the setTimeout function in nextTick(). Assign the setTimeout() function to a variable and then do clearInterval('variable name') in the resetGame function.

    • @cryptolaura8758
      @cryptolaura8758 2 ปีที่แล้ว

      @@michaeld4337 Thanks!

    • @HaiNguyen-fx2tx
      @HaiNguyen-fx2tx 2 ปีที่แล้ว

      @@michaeld4337 many thanks :>

  • @levyroth
    @levyroth 2 ปีที่แล้ว +2

    Shouldn't this be: foodY = randomFood(0, gameHeight - unitSize); in the createFood function?

    • @tintedclown4876
      @tintedclown4876 2 ปีที่แล้ว

      test the code if it doesn't work then it should be your suggestion if it does then it isn't your suggestion

    • @k00lmoh
      @k00lmoh 6 หลายเดือนก่อน +1

      that's correct but in his case gameWidth was == to gameHeight and that's why it works fine

  • @lileshayden9772
    @lileshayden9772 ปีที่แล้ว +1

    I found a bug basically what happens is that you are able to move left then right how it works(your moving left then press up then right really fast you will pass through yourself) not saying this is the best fix but this is what I did
    created 2 variables "thisTick" "lastTick" outside of any function
    this tick increases by one everytime the function nextTick is called (so every tick)
    then lastTick is set to thisTick in every case in the changeDirection function
    with that the case then checks that thisTick is greater then lastTick
    let thisTick;
    let lasTick;
    function nextTick(){
    if(running){
    setTimeout(() => {
    thisTick++
    ___
    switch(true){
    case(keyPressed == LEFT && !goingRight && thisTick > lastTick):
    lastTick = thisTick

  • @XerifeCaitlyn
    @XerifeCaitlyn 2 หลายเดือนก่อน

    Really simple, so great, man

  • @alingamerkid9729
    @alingamerkid9729 ปีที่แล้ว +1

    The snake and the food dont apear on the screen. Can anyone help me please?

    • @RohanAlex-mu9hv
      @RohanAlex-mu9hv ปีที่แล้ว +1

      make sure you're files are named and linked correctly

  • @MeinDeutschkurs
    @MeinDeutschkurs 6 หลายเดือนก่อน

    That’s cool, but why not a global grid array that is rendered afterwards?

    • @k00lmoh
      @k00lmoh 6 หลายเดือนก่อน +1

      that would make it too slow, instead of updating the array then looping over all values and updating the canvas (including tiles/spaces where no changes has occurred) you could just draw the position where changes are going to occur, that way you don't update tiles that hasn't been changed

    • @MeinDeutschkurs
      @MeinDeutschkurs 6 หลายเดือนก่อน

      @@k00lmoh ok. I needed a way to track everything so I had to do it. I uploaded my version to Johannes dot ist slash snake - if you‘re interested into my result.

    • @cd-7089
      @cd-7089 หลายเดือนก่อน

      i made snake with a grid array and it does turn out to be slow, i also ran into errors in checking if the snake collided with a body part even when there was none there. i think its cause its a bit too slow because i exhausted quite a bit of other possibilities.

  • @SoftwareScience
    @SoftwareScience 2 ปีที่แล้ว +1

    Great

  • @bomapdich
    @bomapdich ปีที่แล้ว

    can somebody explain to me the logic behind 11:50. I don't understand why do we have to divide by unitsize just to multiply it back. Wouldn't Math.Round give the same result anyways?

    • @ayushv69
      @ayushv69 ปีที่แล้ว

      Math.random() is a number between 0 to 1 which comes in decimal. So will not get the exact number cause it will be in decimal. For that reason he divide it by unitsize inside math.round () to get exact num. And remove decimal than he again multiplis it outside math.round()

  • @beefycruncwrap
    @beefycruncwrap 8 หลายเดือนก่อน

    i did everything right but nothing showed up still idk what i did wrong because i followed everything

  • @douglasl9150
    @douglasl9150 4 หลายเดือนก่อน

    Great videos in general, this one looks good too. I ran into an error that I cant debug so far on line 20 - ReferenceError: Cannot access 'snake' before initialization
    at index.js:20:13 , see below. any tips?
    let snake = snake [
    {x:unitSize *4, y:0},
    {x:unitSize *3, y:0},
    {x:unitSize *2, y:0},
    {x:unitSize, y:0},
    {x:0, y:0}
    ]

    • @thombre_1
      @thombre_1 2 หลายเดือนก่อน

      snake after the = sign is causing error
      corrected:
      let snake = [
      {x:unitSize*4, y:0},
      {x:unitSize*3, y:0},
      {x:unitSize*2, y:0},
      {x:unitSize, y:0},
      {x:0, y:0}
      ]

  • @maxwellmuhanda7940
    @maxwellmuhanda7940 ปีที่แล้ว

    this is soo nice i used the same concepts to create mine in vue ... very nice video

  • @hailonyp145
    @hailonyp145 2 ปีที่แล้ว +1

    Can someone show me how to change velocity ?
    The velocity is depending on the unitSizeValue here and changing it means changing the whole size of game.
    Tried creating a new variable to use it in the changeDirection but it doesn't worm.

    • @user-ii5qx4vw3q
      @user-ii5qx4vw3q 2 ปีที่แล้ว

      Please send a text on WhatsApp to the number displayed above for guidance.

    • @debabratagon7289
      @debabratagon7289 10 หลายเดือนก่อน

      change the time in setTimeout () to increase speed. the velocity variable is there only to show the displacement.

  • @dcode863
    @dcode863 2 ปีที่แล้ว +1

    hey bro good vid could u maybe do an in browser chess engine next? with pure html css & js. I'm building one ATM but it's difficult. the JS part in particular

  • @samifly2753
    @samifly2753 ปีที่แล้ว

    you are one the best Bro

  • @liridoncani
    @liridoncani 2 ปีที่แล้ว

    I did everything perfect like in video. I have doublechecked ,triplechecked,quadchecked,infinitechecked still cant realise where is the problem.
    I get error unitSize is not defined

    • @shaikhahmed6520
      @shaikhahmed6520 2 ปีที่แล้ว +1

      im not sure if you still have that issue but check line 11 it should say const unitSize = 25;

  • @arthandle2206
    @arthandle2206 2 ปีที่แล้ว

    how are you able to test your code in JS? I cant seem to be able to observe it in liveserver.

  • @krampuswinter5917
    @krampuswinter5917 2 ปีที่แล้ว +2

    What if we want to start at a slow velocity, and then gradually increase with each food?

    • @IRedBerryI
      @IRedBerryI 2 ปีที่แล้ว +1

      add the base velocity by some constant multiplied by the score

    • @cinex20
      @cinex20 ปีที่แล้ว

      @@IRedBerryI Tampering with the velocity value sounds like an easy way to mess things up. It's much safer to just assign nextTick's timeout's value to a global variable and decreasing this variable's value with every food eaten.

  • @steevsonsunny5013
    @steevsonsunny5013 5 หลายเดือนก่อน

    Good bro it's working properly.....

  • @grimmy0769
    @grimmy0769 ปีที่แล้ว

    Where can I get all the code for this quick ( is there a website)

  • @малосольные-окурки
    @малосольные-окурки 6 หลายเดือนก่อน

    cool! nice tutorial

  • @paulthomas1052
    @paulthomas1052 2 ปีที่แล้ว

    Great tutorial. Thanks.

  • @williamdowuona1801
    @williamdowuona1801 ปีที่แล้ว

    Hello brocode can you help me access you social media platforms as well as your website

  • @Siostragraw
    @Siostragraw 3 หลายเดือนก่อน +1

    If i would undarnstand anything😂

    • @Gymrat256
      @Gymrat256 หลายเดือนก่อน

      I feel you bro 😅

  • @debabratagon7289
    @debabratagon7289 10 หลายเดือนก่อน

    Will the recursive function not cause stack overflow?

    • @k00lmoh
      @k00lmoh 6 หลายเดือนก่อน +2

      if you keep going in circles without progression for too long probably yes

  • @jowawhatdos4134
    @jowawhatdos4134 2 ปีที่แล้ว +15

    How can you make this downloadable in android after you finish ????

    • @8xnnr
      @8xnnr ปีที่แล้ว

      How can you

    • @syedyousuffaizan1779
      @syedyousuffaizan1779 ปีที่แล้ว +1

      React native maybe?

    • @thereisnoname2052
      @thereisnoname2052 10 หลายเดือนก่อน

      You can search on Google how to build PWA .

    • @k00lmoh
      @k00lmoh 6 หลายเดือนก่อน

      take a look at Electron/Tauri

    • @AndroidDevsTutorials
      @AndroidDevsTutorials 4 หลายเดือนก่อน

      You Can Add The HTML, CSS & JavaScript File In Your Project Asset Folder Then Use A WebView To Render It.

  • @Momo-iq6uu
    @Momo-iq6uu ปีที่แล้ว

    You're DA BEST

  • @Mind--Blow
    @Mind--Blow ปีที่แล้ว

    made it thanks for the work!!!!

  • @HRUstudent
    @HRUstudent 4 หลายเดือนก่อน

    thank you i also added another feature 😍😍😍

  • @reinkdesigns
    @reinkdesigns 2 ปีที่แล้ว

    an issue im curious how you fix, while you cant press left while moving right, if you press down left within the 75ms of each other the snake doubles back on itself. obliviously it gets worse if you say for instance wanna make a difficulty slider that just lowers the game speed
    eww 2nd bug im cant figure out, while playing if you press reset, then keep pressing spacebar, the snake gets faster and faster?? nothing i see in the code is making the game speed more than 75 tho?

    • @mibrahim2001
      @mibrahim2001 2 ปีที่แล้ว

      About the second bug what you can do is create a gobal variable for timeout and store setTimeout() in that variabe in nextTick() function. Then in the reset function do this clearTimeout(*your variable name*)

    • @reinkdesigns
      @reinkdesigns 2 ปีที่แล้ว

      @@mibrahim2001 ok cool, thanks

    • @cinex20
      @cinex20 ปีที่แล้ว

      Managed to fix that by buffering the inputs to prevent multiple actions between ticks.
      let nextTurn;
      function changeDirection(event) {
      const keyPressed = event.keyCode;
      const LEFT = 37;
      const UP = 38;
      const RIGHT = 39;
      const DOWN = 40;

      const goingUp = (yVelocity == -unitSize);
      const goingDown = (yVelocity == unitSize);
      const goingRight = (xVelocity == unitSize);
      const goingLeft = (xVelocity == -unitSize);
      switch (true) {
      case (keyPressed == LEFT && !goingRight):
      nextTurn = "turnLeft";
      break;
      case (keyPressed == UP && !goingDown):
      nextTurn = "turnUp";
      break;
      case (keyPressed == RIGHT && !goingLeft):
      nextTurn = "turnRight";
      break;
      case (keyPressed == DOWN && !goingUp):
      nextTurn = "turnDown";
      break;
      }
      };
      function turn(){
      switch(true) {
      case (nextTurn == "turnLeft"):
      xVelocity = -unitSize;
      yVelocity = 0;
      break;
      case (nextTurn == "turnUp"):
      xVelocity = 0;
      yVelocity = -unitSize;
      break;
      case (nextTurn == "turnRight"):
      xVelocity = unitSize;
      yVelocity = 0;
      break;
      case (nextTurn == "turnDown"):
      xVelocity = 0;
      yVelocity = unitSize;
      break;
      }
      };
      In the nextTick() function, put turn() before moveSnake(). Don't forget to also set nextTurn to null in the resetGame() function, just before resetting the velocity values.

  • @programmer2427
    @programmer2427 2 ปีที่แล้ว +3

    I cannot get it to work cause of
    Uncaught TypeError: Cannot set properties of null (setting 'textContent')
    at gameStart (BrocodesnakeGame.js:33:27)
    at BrocodesnakeGame.js:29:1

    • @mjc7747
      @mjc7747 ปีที่แล้ว

      Mine was doing that as well. I figured out that in the .html document I named the 'div id=score' rather than scoreText.


      0
      Reset

  • @TheGamerDK2009
    @TheGamerDK2009 2 ปีที่แล้ว +1

    Which app is it?

  • @TheJonathan9998
    @TheJonathan9998 2 ปีที่แล้ว

    What tutorial did he explain how and why you use JavaScript and css with html ect

  • @Dev_ps2
    @Dev_ps2 8 หลายเดือนก่อน

    Can I add it to my github?

  • @themountains1701
    @themountains1701 2 ปีที่แล้ว

    Hey Bro! There is an issue in this game.
    When you click two buttons(up, down, left, right) very fast one after another like DOWN, LEFT the game shows GAME OVER! Can you tell why?

    • @lileshayden9772
      @lileshayden9772 ปีที่แล้ว

      its because the snake moves into itself if you are moving "RIGHT" then click "DOWN" "LEFT" the snake moves in itself its a bug within the code currently trying to figure it out
      EDIT**
      Okay so not saying this is the best fix but what I did
      created 2 variables "thisTick" "lastTick" outside of any function
      this tick increases by one everytime the function nextTick is called (so every tick)
      then lastTick is set to thisTick in every case in the changeDirection function
      with that the case then checks that thisTick is greater then lastTick
      let thisTick;
      let lasTick;
      function nextTick(){
      if(running){
      setTimeout(() => {
      thisTick++
      _____
      switch(true){
      case(keyPressed == LEFT && !goingRight && thisTick > lastTick):
      lastTick = thisTick

    • @cinex20
      @cinex20 ปีที่แล้ว

      Managed to fix that by buffering the inputs to prevent multiple actions between ticks.
      let nextTurn;
      function changeDirection(event) {
      const keyPressed = event.keyCode;
      const LEFT = 37;
      const UP = 38;
      const RIGHT = 39;
      const DOWN = 40;

      const goingUp = (yVelocity == -unitSize);
      const goingDown = (yVelocity == unitSize);
      const goingRight = (xVelocity == unitSize);
      const goingLeft = (xVelocity == -unitSize);
      switch (true) {
      case (keyPressed == LEFT && !goingRight):
      nextTurn = "turnLeft";
      break;
      case (keyPressed == UP && !goingDown):
      nextTurn = "turnUp";
      break;
      case (keyPressed == RIGHT && !goingLeft):
      nextTurn = "turnRight";
      break;
      case (keyPressed == DOWN && !goingUp):
      nextTurn = "turnDown";
      break;
      }
      };
      function turn(){
      switch(true) {
      case (nextTurn == "turnLeft"):
      xVelocity = -unitSize;
      yVelocity = 0;
      break;
      case (nextTurn == "turnUp"):
      xVelocity = 0;
      yVelocity = -unitSize;
      break;
      case (nextTurn == "turnRight"):
      xVelocity = unitSize;
      yVelocity = 0;
      break;
      case (nextTurn == "turnDown"):
      xVelocity = 0;
      yVelocity = unitSize;
      break;
      }
      };
      In the nextTick() function, put turn() before moveSnake(). Don't forget to also set nextTurn to null in the resetGame() function, just before resetting the velocity values.

  • @tamimaldaher3461
    @tamimaldaher3461 2 ปีที่แล้ว

    this guy is a legend

  • @thereisnoname2052
    @thereisnoname2052 10 หลายเดือนก่อน

    14:20
    Can i ask why you used setTimeOut instead of setInterval ?

    • @k00lmoh
      @k00lmoh 6 หลายเดือนก่อน

      this is because the function `nextTick()` is a recursive function, it keeps calling itself until a condition is met (exit condition), using setInterval would be like using a loop inside of a loop and we only need to loop once.
      hope that makes sense

  • @fr1endsies
    @fr1endsies 2 ปีที่แล้ว

    Thank you

  • @uniquecode-tech
    @uniquecode-tech 2 ปีที่แล้ว

    You are the best man

  • @basscat8110
    @basscat8110 2 ปีที่แล้ว

    💪💪💪

  • @aimeblack
    @aimeblack 2 ปีที่แล้ว

    What IDE are you using?

    • @ZaturateEDM
      @ZaturateEDM 3 หลายเดือนก่อน +1

      Visual Studio Code. It’s free to download also.

    • @aimeblack
      @aimeblack 3 หลายเดือนก่อน

      @@ZaturateEDM hello my friend, thank you for answering me, i already found the app and i been using it for awhile but thank you for asking my friend ^^

  • @ezmn4gdas
    @ezmn4gdas 2 ปีที่แล้ว +1

    I'm surprised you didn't use 'python' for your 'snake' game

  • @homan-awa
    @homan-awa 2 ปีที่แล้ว

    finally i can write snake in python, java and javascript. c++ next maybe ? :D

  • @nerrixj.l.6102
    @nerrixj.l.6102 2 ปีที่แล้ว

    😍

  • @martinkobimbo8090
    @martinkobimbo8090 ปีที่แล้ว

    What a Chad!

  • @osimigodsgift8565
    @osimigodsgift8565 2 ปีที่แล้ว

    THANKS SO MUCH, CAN I POST IT ON MY TWITTER ACCOUNT OR REPLIT ACCOUNT,OR ON GIT HUB OR I NEED SOME KIND OF COPYRIGHT ORDER FROM YOU @Bro code

  • @sparkscomputerprogramming
    @sparkscomputerprogramming 2 ปีที่แล้ว

    great tutorial bro i need your help though, how CAN I CONTACT YOU?

  • @S-Lomar
    @S-Lomar ปีที่แล้ว

    Thank you for sharing your experience with us ♥️💕❤️😍💙❤️😍😍😍😍😍🥰😍😍😍😍😍❤️❤️💋💋❤️❤️💋💋 why you not talking 'bout earning on it💞💞💓💕💕💞💞💕🥰💕💞😂💓🥰🥰💓💓💕