Troubleshooting the inefficiency of pausing a JavaScript game through style.display in conditional statements

I've been working on a JavaScript game and I'm facing an issue with adding code to the button that toggles the game's visibility and acts as a pause button. I want the game to stop running and not bombard you with scoring alerts if it is hidden, but unfortunately all the code I've tried so far has failed. Here is what I have, hoping someone can assist me in fixing it.

<div id = 'games'>
<!-- This canvas is enclosed in a div for future expansion. -->
<canvas id='my' width='640' height='480'></canvas>
</div>

<script>
var canvas = document.getElementById("my");
var ctx = canvas.getContext("2d");

function paddle(x, y, width, height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.speedModifier = 0;
    this.hasCollidedWith = function(ball) {
        var paddleLeftWall = this.x;
        var paddleRightWall = this.x + this.width;
        var paddleTopWall = this.y;
        var paddleBottomWall = this.y + this.height;
        if (ball.x > paddleLeftWall && ball.x < paddleRightWall && ball.y > paddleTopWall && ball.y < paddleBottomWall) {
            return true;
        }
        return false;
    };
    this.move = function(keyCode) {
        var nextY = this.y;
        if (keyCode == 40) {
            nextY += 5;
            this.speedModifer = 1.5;
        } else if (keyCode == 38) {
            nextY += -5;
            this.speedModifier = 1.5;
        } else {
            this.speedModifier = 0;
        }
        nextY = nextY < 0 ? 0 : nextY;
        nextY = nextY + this.height > 480 ? 480 - this.height : nextY;
        this.y = nextY;
    };
}
var player = new paddle(5, 200, 25, 100);

var ai = new paddle(610, 200, 25, 100);
var ball = {
    x: 320,
    y: 240,
    radius: 7,
    xSpeed: 2,
    ySpeed: 0,
    playerscore: 0,
    aiscore: 0,
    reverseX: function() {
        this.xSpeed *= -1;
    },
    reverseY: function() {
        this.ySpeed *= -1;
    },
    reset: function() {
        alert('The score is now ' + this.playerscore + ' to ' + this.aiscore);
        this.x = 20;
        this.y = 24;
        this.xSpeed = 2;
        this.ySpeed = 0;
        
    },
    isBouncing: function() {
        return ball.ySpeed != 0;
    },
    modifyXSpeedBy: function(modification) {
        modification = this.xSpeed < 0 ? modification * -1 : modification;
        var nextValue = this.xSpeed + modification;
        nextValue = Math.abs(nextValue) > 9 ? 9 : nextValue;
        this.xSpeed = nextValue;
    },
    modifyYSpeedBy: function(modification) {
     
   modification = this.ySpeed < 0 ? modification * -1 : modification;
        this.ySpeed += modification;
    }
};
function tick() {
   
   updateGame();
    draw()
    window.setTimeout("tick()", 1000 / 60);
}

function updateGame() {
    ball.x += ball.xSpeed;
    ball.y += ball.ySpeed;
    if (ball.x < 0) {
        ball.reset();
        ball.aiscore = ball.aiscore + 1;
        
    }
    if (ball.x > 640) {
        ball.reset();
        ball.playerscore = ball.playerscore + 1
        
    }
    if (ball.y <= 0 || ball.y >= 480) {
        ball.reverseY();
    }
    var collidedWithPlayer = player.hasCollidedWith(ball);
    var collidedWithAi = ai.hasCollidedWith(ball);
    if (collidedWithPlayer || collidedWithAi) {
        ball.reverseX();
        ball.modifyXSpeedBy(0.25);
        var speedUpValue = collidedWithPlayer ? player.speedModifier : ai.speedModifier;
        ball.modifyYSpeedBy(speedUpValue);
    }
    for (var keyCode in heldDown) {
        player.move(keyCode);
    }
    var aiMiddle = ai.y + (ai.height / 2);
    if (aiMiddle < ball.y) {
        ai.move(40);
    }
    if (aiMiddle > ball.y) {
        ai.move(38);
    }
    
}

function draw() {
    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, 640, 480);
    renderPaddle(player);
    renderPaddle(ai);
    renderBall(ball);
}

function renderPaddle(paddle) {
    ctx.fillStyle = "blue";
    ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
}

function renderBall(ball) {
    ctx.beginPath();
    ctx.arc(ball.x, ball.y, ball.radius, 0, 2 * Math.PI, false);
    ctx.fillStyle = "pink";
    ctx.fill();
}
var heldDown = {};
window.addEventListener("keydown", function(keyInfo) {
    heldDown[event.keyCode] = true;
}, false);
window.addEventListener("keyup", function(keyInfo) {
    delete heldDown[event.keyCode];
}, false);
function playPong(){
 if (canvas.style.display == 'none'){canvas.style.display = 'block';}
 else {canvas.style.display == 'none';}
if (canvas.style.display === 'block')
{
tick()};

}



</script>

<script>
function hide() {
var games = document.getElementById('games')
if (games.style.display === 'block')
games.style.display = 'none';
else{games.style.display = 'block';}
}
function show(){
var canvas = document.getElementById('my')
canvas.style.display = 'block';
}
</script>


<button onclick='hide()'> Hide or show the games</button>

<button onclick='playPong();show()'> Play pong </button>

Answer №1

I suggest refraining from relying on the visibility of the canvas to determine the outcome within the if statement. Consider utilizing an approach similar to this:

<div id='games'>
  <canvas id='my' width='640' height='480'></canvas>
</div>
...
(Button controls and functions for hiding, showing, pausing, and playing games are provided in the code snippet)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it acceptable to display certain IDs in HTML?

Is it acceptable to structure an HTML page like the following: ... <div id='some_id' lesson_id='313'> ... </div> ... And then in jQuery simply retrieve the lesson_id: lesson_id = $("#some_id").attr("lesson_id") // make A ...

Ways to recycle the table feature in angular2?

I am new to Angular2 framework and I am looking to efficiently reuse a single table component across my entire application. However, I am encountering challenges when it comes to displaying arrays in the table rows. How can I iterate through any type of ar ...

Why is it that the bootstrap text color class isn't applying for my project?

After some experience with bootstrap, I have encountered an issue with the text-white class. Despite trying to change the text color using this class, it doesn't seem to work. Below is the code that I've been working on. Can anyone spot what migh ...

Show all information from MySQL tables in an HTML format

I need help with displaying an entire mysql table within an HTML table. I've come across some code that is able to show the fields: <?php $con=mysqli_connect("example.com","peter","abc123","my_db"); // Check connection if(mysqli_connect_e ...

Order a portion of a JSON array according to another part of the same array

Having a json array that needs sorting in JavaScript. The EventName field should match the respective Age fields like 01-10 Days and 10-20 Days. [ {Age: "01-10 Days", EventName: "Invoice AP Review", Value: 1, ActiveInvoices: []} ,{Age: "01-10 Days", Even ...

Verify whether an HTML element lies within another HTML element

Consider this example: <div id="President"> <div id="Congressman"> <div id="Senator"> <div id="Major"></div> </div> </div> </div> Is there a simple way in JavaScript or jQuery to determine ...

Using JQuery, retrieve the input from a text box within a table and save it as a variable

I am facing an issue with extracting and storing a variable from a textbox located within a dynamically generated table. My objective is to retrieve the value from the textbox within the dynamically generated table, and then save it to the database. The ...

Refreshing and reloading within the same jQuery function

My PHP application involves the use of 2 PHP files. chart.php - This page includes a Google chart. <div id="chart_div" style="height:100%;width:100%"> </div> <script type="text/javascript"> google.charts.load('current', ...

What is the best location to manage errors within a sequelize ORM query?

I am working with the Sequelize ORM within a Node/Express environment. My database has two tables: one for Users and another for Items. The Item table includes a foreign key that is linked to the UserId in the User table. Whenever I attempt to create an ...

Modifying `msg.sender` in Solidity and Ether.js

I have a Smart Contract written in Solidity. Within this contract, there is a function called makeMarketItem. function makeMarketItem( address nftContract, uint256 tokenId, uint256 price ) public payable nonReentrant { IERC721(nftContract). ...

Steps for generating a unique object with the field name as the key in MongoDB

Modifying the outcome of an aggregation query where the field name serves as the key in the database. I attempted the following: How to utilize field value as key name in Mongodb result However, it resulted in the subsequent error: MongoError: $array ...

Tips for activating a tkinter scrollbar in a disabled state

I'm currently developing a tkinter application that displays images each time a user clicks a button. I want to implement a scroll bar so users can easily navigate through the images that are off-screen. However, for some reason, my scroll bar appears ...

What is the best way to delete the material-dashboard-react text from the starting route in a material ui admin panel?

When launching my React web application, I am initially directed to localhost:3000/material-dashboard-react, which then redirects to /. However, this redirect is briefly visible before the web app fully loads. Can anyone advise on how to remove this initia ...

What is the best method for clearing form validation when using a create modal?

I'm facing a dilemma in this situation. Whenever I click on + Rule, it triggers the function below: showAddRuleModal() { this.showAddRule = true this.$refs.form.reset() //reset form values this.ruleName = '' this.url = ...

Tips for adjusting the dimensions of an SVG background within an element using the gulp-svg-sprite npm package

My current project involves the use of an NPM package called gulp-svg-sprite, which consolidates all my SVG images into a single file named sprites.svg and also generates sprites.css. Within the sprites.css file, there are CSS classes that define their ba ...

NuxtJS using Babel 7: the spread operator persists in compiled files

Struggling to get my NuxtJS app functioning properly on IE11. Despite multiple attempts to configure Babel for compatibility, spread operators are still present in the built pages files, suggesting that Nuxt code is not being transformed correctly. Below ...

Querying Parse Server for objectId information

Within my web app that utilizes the Parse Server Javascript SDK, I have implemented the following query. While the console log accurately displays the retrieved information, the objectId field appears as "undefined." var query = new Parse.Query("myClass") ...

Having difficulty aligning dynamic lists with their container on a horizontal navigation menu

I am trying to create an expanding list that drops relative to the parent's position. Right now, I have set the position to absolute, which lines up the lists incorrectly. When I change it to relative positioning, I get the desired result but there is ...

Having trouble accessing the downloaded file from S3 using Angular and NodeJS

Currently, I am facing an issue while attempting to download a jpg image from amazon S3 using the NodeJs SDK. Although I can successfully retrieve the file object on the backend, encountering difficulties arises when trying to create a blob object and down ...

Are MobX Observables interconnected with RxJS ones in any way?

Is the usage of RxJs observables in Angular comparable to that in React and MobX? I'm struggling to find information on this topic. ...