What are the steps to reset a JavaScript game?

I'm currently working on a JavaScript game project. Once the game is finished, I'd like to give players the option to go back to the main menu by clicking a button, then start a new game by clicking play again. However, I've run into an issue where reloading the game after clicking play sends me back to the game over screen with the previous score displayed.

var keys = [];
var health = 100;
var score = 0;
var scene = "menu";
var clicked = false;
keyPressed = function() {
  keys[keyCode] = true;
};
keyReleased = function() {
  keys[keyCode] = false;
};

textFont(createFont("calibri", 35));

//Buttons
var button = function(cJ) {
  this.x = cJ.x;
  this.y = cJ.y;
  this.w = cJ.w;
  this.h = cJ.h;
};
button.prototype.mouseIsOver = function() {
  return (
    mouseX > this.x &&
    mouseX < this.x + this.w &&
    mouseY > this.y &&
    mouseY < this.y + this.h
  );
};
button.prototype.draw = function() {
  noStroke();
  textAlign(CENTER);
  if (this.mouseIsOver() === true) {
    fill(232, 232, 232);
    rect(this.x + 3, this.y - 3, this.w, this.h);
  } else if (this.mouseIsOver() === false) {
    fill(255, 255, 255);
    rect(this.x + 3, this.y - 5, this.w, this.h);
  }
};
var playButton = new button({
  x: width / 2 - 60,
  y: height / 2 + 21,
  w: 120,
  h: 45
});
var howButton = new button({
  x: width / 2 - 60,
  y: 284,
  w: 120,
  h: 45
});
var backButton = new button({
  x: width / 2 - 197,
  y: 365,
  w: 70,
  h: 30
});
var restartButton = new button({
  x: width / 2 - 102,
  y: 250,
  w: 200,
  h: 36
});

var menuC = function() {
  if (howButton.mouseIsOver()) {
    how();
  } else if (playButton.mouseIsOver()) {
    game();
  }
};
var howC = function() {
  if (backButton.mouseIsOver()) {
    menu();
  }
};
var loseC = function() {
  if (restartButton.mouseIsOver()) {
    Program.restart();
  }
};
mouseClicked = function() {
  if (scene === "menu") {
    menuC();
  } else if (scene === "how") {
    howC();
  } else if (scene === "lose") {
    loseC();
  }
};

//Menu Text
draw = function() {
  if (scene === "menu") {
    menu();
    //Title
    textSize(47);
    fill(41, 207, 182);
    text("ACIDIC RAIN", 207, 147);

    //Buttons
    playButton.draw();
    howButton.draw();

    textSize(30);
    fill(41, 207, 182);
    text("PLAY", 202, 248);
    text("HOW", 202, 311);
  }
  if (scene === "game") {
    game();
  }
  if (scene === "how") {
    how();
    backButton.draw();
    fill(41, 207, 182);
    textSize(17);
    text("BACK", 40, 380);
  }
  if (scene === "lose") {
    lose();
    restartButton.draw();
    fill(0);
    textSize(20);
    text("GO BACK TO MENU", 201, 270);
  }
};

Answer №1

The reason for this behavior is due to the fact that your variables are all declared within the global scope at the beginning of the JavaScript code. As a result, when you call methods like game() or menu(), they simply use the existing values stored in those variables.

A better approach would be to encapsulate the entire code snippet you provided within a "class", where both the variables and methods belong to the class. By doing so, you can easily reset all local variables within the class instance by destroying the current instance upon button click and creating a new one in its place. This effectively erases any previous progress made.

For more information on using classes in JavaScript, refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

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

What is the reason for the error occurring in express.js?

I encountered an issue when I added this snippet of JavaScript to an HTML page being served by express.js. What could be causing the error? <script> var foo = /<%([\s\S]+?)%>/g; </script> Error: 500 SyntaxErro ...

Are you facing issues with Handlebars parsing?

I am struggling to identify the issue in my HTML/JS code. Here is my HTML/JS: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="handlebars-v1.1.2.js"> ...

jQuery behaving erratically following deployment to the testing server

I am encountering an issue with jQuery in a user control that utilizes a Telerik RadGrid: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js"></script> <script type="text/javascript"> ...

Identifying the completion of scrolling within a container

I'm facing a challenge with my dynamic website that has numerous blog posts. My goal is to initially load only four posts and then add another four as the user scrolls to the end of the page. While I have figured out how to handle this on the backend, ...

Guide on sending information using ajax using a button within a form

I've been working on creating a form that utilizes HTML5 validations and integrates Ajax to show the status of mail sending. However, I'm facing an issue where clicking the send button does not initiate the expected action. Form HTML: <div c ...

Regular expression: Search for a particular word following the initial appearance of a backslash

I need help with creating a regex pattern to find the word "bacon" after the first "/" in a URL. Here are some examples: Expected to return true: console.log('1 - ', myRegexFunction('www.bacondelivery.com/weekly-bacon-delivery/')); co ...

Exploring Next.js: Comparing data fetching in getInitialProps(): server-side versus client-side

Currently, I'm working with Next.js and have set up a custom server using Express. One of my pages needs to retrieve data from the database. When getInitialProps() is executed on the server side, it easily retrieves the necessary data from the databa ...

Using a JavaScript function to post the input value and then displaying it through PHP

I am striving to create an input field that will capture the value of what is typed and display it. The JavaScript function is designed to retrieve the value of the input box two seconds after the user stops typing and then post it. However, the issue lies ...

What is the best way to insert an object at a particular position within an array containing numerous nested objects?

This is the given Object: [ { "id": "1709408412689", "name": "WB1", "children": [ { "id": "1709408412690", "n ...

I'm curious about how to properly escape single quotes when passing a variable in a Java argument call using Karate DSL. Can you help

As part of our API project at work, I am looking to incorporate database calls into our end-to-end process. One challenge I am facing is how to handle single quotes within a variable that is passed as an argument in an assert method. I have attempted the f ...

Step-by-step guide on how to have an AngularJS controller run continuously every 5 seconds once it has been initially called

My angular js file (app.js) contains the uuidCtrl controller, which triggers when called. When I want to call the controller 2 times, I have to load the page twice. However, I am looking for a solution to run it continuously after the first time it is call ...

Verify and deselect boxes

Can someone help me with checking and unchecking checkboxes? I'm facing a lot of issues with it. You can find my code snippet here: http://jsfiddle.net/N5Swt/: <input type="checkbox" id="checkbox1" /> <span> Check me! </span> // ...

What is the process for integrating three.js code manually into an iframe?

I recently posted a question on Stack Overflow inquiring about how to input code into an iframe without using a file or URL. While I was successful with simple cases like <h1>Hello World</h1>, my ultimate goal is to integrate three.js into thes ...

Encountering problems with createMediaElementSource in TypeScript/React when using the Web Audio API

Currently, I am following a Web Audio API tutorial from MDN, but with a twist - I am using TypeScript and React instead of vanilla JavaScript. In my React project created with create-react-app, I am utilizing the useRef hook to reference the audio element ...

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...

Ways to delete added text from a Cookie

My cookie stores strings that are appended to it, and when a user clicks a button, I want to be able to remove the specific string that was clicked while keeping the existing strings in the cookie intact. The functions needed for this operation are trigger ...

Transformation of looks post a refresh

Initially, the CSS and appearance of the page look fine when I first open it (after clearing the cache). However, upon refreshing the page, a part of it changes (specifically, the padding direction of a div). This change occurs consistently with each refre ...

Limiting Node.js entry with Express

I have a node.js script running on a server. I want to prevent it from being accessed directly from a browser and restrict access to only certain domains/IP addresses. Is this achievable? ...

Modify the Ag-Grid Tree Structure by hiding the Ids in the autoGroupColumn

I am currently utilizing ag-grid for visualizing a tree structure. Each row in my data contains an Id and a parent Id, which establishes the tree hierarchy. When I display Ag-grid, an extra column displaying the row Id appears. As I navigate through the tr ...

Error: The provided `anchorEl` property for this component is invalid

While working on my React 18.2 app with MUI 5.10.5, I encountered an issue trying to create a <Menu /> element that should open when a button is clicked. The menu does appear, but the positioning seems off as it displays in the top-left corner of the ...