How to reset my game to its previous state when I am using HTML Canvas

This is my ping pong game.

The game ends once the ball hits the left side three times.

I want a solution through which I can reset the game once the game ends and I can start a new one .

But I am finding it difficult to do maybe because the canvas behaves abnormally. Any solution to this problem?

And also after reset the mouseover thing stops working .

  • notice that I have used the same function for both game starts and game ends message box inside the html file on click event .
    My html script
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="start" onclick="gameloop('start')">
        Click any where to continue
    </div>
    <div id="gameover" onclick="gameloop('gameover')">
        Game Over! <br> Click any where to continue
    </div>
    <canvas id="canvas"></canvas>
    <script src="script.js"></script>
</body>

My Css stylesheet

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
}

body {
    width: 100vw;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 255, 0.5);
}

#gameover {
    display: none;
    width: 100vw;
    height: 100vh;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    background-color: rgba(247, 14, 14, 14, 0.7);
}

#start {
    position: fixed;
    z-index: 1;
    width: 100vw;
    height: 100vh;
    line-height: 100vh;
    text-align: center;
    font-size: xx-large;
    background-color: rgba(14, 14, 247, 0.7);
}

My javascript code

let canvas = document.getElementById("canvas");
let canvasX = 0,
    canvasY = 0;

canvas.width = window.innerWidth - 100;
canvas.height = window.innerHeight - 100;

// Game logic
let tick;
let gameEnd = false;
let mistakeCount = 0;
let playerHeights = 150;
let executed = false;
let ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";

// canvas
let cw = canvas.width;
let ch = canvas.height;
ctx.fillRect(canvasX, canvasY, cw, ch);

// player who is playing
let playerPos = ch / 2;
ctx.fillStyle = "white";
ctx.fillRect(10, playerPos, 10, playerHeights);

// ball position
let ballX = cw / 2,
    ballY = ch / 2,
    ballHorizontalDirection = true, //right side
    ballAngle = 5; // The amount of pixels the ball has to move upwards

ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(ballX, ballY, 10, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();

// computer player
let computerPos = ch / 2;
ctx.fillStyle = "white";
ctx.fillRect(cw - 20, computerPos, 10, playerHeights);

function gameloop(buttonId) {
    document.addEventListener("mousemove", (e) => {
        // e.clientX,e.clientY
        playerPos = e.clientY;
    });
    document.getElementById(buttonId).style.display = "none";
    let i = 0;
    draw();
}

function resetTheGame() {
    cancelAnimationFrame(tick);
    document.getElementById("gameover").style.display = "flex";
    executed = false;
    gameEnd = false;
    mistakeCount = 0;
    playerPos = ch / 2;
    ballX = cw / 2;
    ballY = ch / 2;
    ballHorizontalDirection = true; //right side
    ballAngle = 5;
    computerPos = ch / 2;
}

function checkForPlayerCollision() {
    if (ballX <= 25 && ballY < playerPos + playerHeights && ballY > playerPos) {
        ballHorizontalDirection = !ballHorizontalDirection;
        let firstHalf = playerPos + playerHeights / 2;
        if (ballY > firstHalf + 20) {
            ballAngle = 5;
        } else if (ballY > firstHalf - 20 && ballY < firstHalf + 20) {
            ballAngle = 0;
        } else {
            ballAngle = -5;
        }
    }
    if (ballX >= cw - 20) {
        ballHorizontalDirection = !ballHorizontalDirection;
    }
}

function selectBallPosition() {
    if (ballHorizontalDirection) {
        ballX += 5;
    } else {
        ballX -= 5;
    }
}

function gameEnds() {
    if (!executed) {
        if (ballX >= cw || ballX <= 5) {
            if (mistakeCount == 2) {
                alert("Game End");
                executed = true;
                resetTheGame();
                return true;
            }
            ballHorizontalDirection = !ballHorizontalDirection;
            mistakeCount++;
            return false;
        }
        return false;
    }
    return true;
}

function setPlayerPositions() {
    if (playerPos + playerHeights >= ch - 40 || playerPos <= 20) {
        playerPos = playerPos;
    }
    if (computerPos + playerHeights >= ch - 20 || computerPos <= 20) {
        computerPos = computerPos;
    }
}

function checkForTopBottomCollision() {
    if (ballY <= 10 || ballY >= ch - 20) {
        ballAngle = -1 * ballAngle;
    }
}

function draw() {
    cancelAnimationFrame(tick);
    ctx.clearRect(10, 10, cw, ch);

    // context
    ctx.fillStyle = "blue";
    ctx.fillRect(10, 10, cw, ch);

    // player
    ctx.fillStyle = "white";
    ctx.fillRect(10, playerPos, 10, playerHeights);
    ballY += ballAngle;

    // computer
    ctx.fillStyle = "white";
    ctx.fillRect(cw - 20, ballY - 20, 10, playerHeights);

    // ball
    ctx.fillStyle = "white";
    ctx.beginPath();
    ctx.arc(ballX, ballY, 10, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();

    // frame
    ctx.fillStyle = "gray";
    ctx.beginPath();
    ctx.lineWidth = "20";
    ctx.rect(0, 0, cw, ch);
    ctx.stroke();

    // dotted line in between
    ctx.beginPath();
    ctx.lineWidth = "1";
    ctx.setLineDash([20, 5]);
    ctx.moveTo(cw / 2, 0);
    ctx.lineTo(cw / 2, ch);
    ctx.stroke();
    ctx.setLineDash([]);
    ctx.closePath();

    // score board for player
    ctx.fillStyle = "skyblue";
    ctx.font = "100px Arial, Helvetica, sans-serif";
    ctx.fillText("0", cw / 2 - 150, ch / 2 + 35);

    // score board for computer
    ctx.fillText(mistakeCount, cw / 2 + 100, ch / 2 + 35);

    if (!gameEnd) {
        tick = requestAnimationFrame(draw);
        selectBallPosition();
        setPlayerPositions();
        checkForPlayerCollision();
        checkForTopBottomCollision();
        gameEnd = gameEnds();
    }
}

If you want to answer me at stackoverflow go here

Hey @krishnasai3cks!

I went to stackoverflow and saw that you had solved the problem.

If you have future issues that you want to share that requires posting a lot of code you may have better luck sharing a codepen link or js fiddle link to the forum. That way people can mess around with the code in there and give you feedback based on their observations.

Happy coding!

1 Like

Thank you I will take this into consideration next time.