Enhanced game experience with Java servlet and JavaScript: Sending multiple requests to a single servlet for updating game status

My setup includes:

  • a Java class named Game.java, containing an array of integers representing a game field and a method to update this field
  • a servlet named StartServlet, which creates a new instance of Game, updates it once, and sends a JSON response with the updated field
  • and a JavaScript function called updateState(), responsible for taking the response from the servlet and updating the document based on it:

    public class Game  {
       private int[][] field;
    
       public Game(int size)  {
         //creates a field of integers with dimensions int[size][size] and randomly populates it with 1s and 0s
       }
    
       public void update()  {
         //updates the field (replaces 1s or 0s), following specific rules
       }
    
       public String toString()  {
         //returns a String representation of the field array
       }
    
       public int[][] getField()  {return field;}
    }
    

In addition, there is a Servlet that utilizes the Game class:

public class StartServlet extends HttpServlet {
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONArray jsonArray = new JSONArray();
        Game game = new Game(15);
        game.update();   

        for (int i=0; i<game.getField().length; i++)  {
          //converts data from the game's field to JSON format
       }

       response.getWriter().println(jsonArray.toString());
     }
}

When a button is clicked on the front end, JavaScript takes the JSON array returned by the StartSevlet

$(document).on("click", "#start-button", function () {  
            //update game state every second
            var timerId = setInterval(updateState, 1000);

            //do it for 5 seconds  
            setTimeout(function() {  
                clearInterval(timerId);
                alert( 'stop' );
            }, 5000);
});

function updateState()  {
        getResponseField(drawFieldJSON);
}

function getResponseField(callback)  {
    //fetches JSON array from the servlet and stores it in a JavaScript array

    callback(responseField);
}

function drawFieldJSON(responseField)  {
    //modifies the document's div elements according to the response array
}

I am trying to continuously update the game's state using a loop in JavaScript:

var timerId = setInterval(updateState, 1000);  //update game state every second
setTimeout(function() {  //run for 5 seconds
  clearInterval(timerId);
  alert('stop');
}, 5000);

However, the game does not seem to change because a new request is sent to the servlet each time, resulting in a new instance of Game being created. I am unsure how to modify this behavior or if it is even feasible.

Answer №1

Keep the Game object stored in the session and retrieve it for each request. This way, it will be incremented with every new request.

Answer №2

Declare the Game object as static in the servlet class: static Game game = new Game(15); Static fields in a servlet will persist not only across all sessions and requests but for the entire duration of the application, until the web application is undeployed.

If you encounter any issues or require further updates, please leave a comment and I will provide the necessary code changes.

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

Error encountered in checking the billing address during AJAX checkout on WooCommerce

I am encountering an issue with WooCommerce's checkout form (running on WooCommerce version 2.4.7). I have enabled guest purchases for a physical product with an option to register, and I have disabled the cart as it is unnecessary for my setup. Howev ...

Toggle between a list view and grid view for viewing photos in a gallery with a

Hey there, I'm a newbie on this site and still getting the hang of jQuery and JavaScript. Though I do have a good grasp on HTML and CSS. Currently, I'm working on a photo gallery webpage as part of my school project using the Shadowbox plugin. Wh ...

Error: The data from the intermediate value cannot be parsed using the parseFromString() method and replaced with another value,

I'm working on a project where I need to display parsed HTML content within an element. However, before displaying it, I need to make some changes to the HTML using the `replace` method. But unfortunately, I encountered a TypeError: (intermediate valu ...

Unleash the full potential of React and material-ui with the Raised Button feature - find out how to effortlessly keep all

This snippet showcases the code for my custom Buttons component: import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; const style = { button: { margin: 2, padding: 0, minWidth: 1, }, }; cons ...

Can anyone explain how to successfully implement AJAX data in a PHP file?

I've been struggling to transfer data from my JavaScript file to a PHP variable. I've spent hours searching for solutions, but none seem to apply to my unique code. Here's the JavaScript code I'm working with... $(function(){ ...

Having trouble setting a URI path for an image in an ImageView on Android Studio

I'm currently working on creating two apps that need to communicate with each other through a content provider. The content provider is functioning properly and data is successfully being transferred between the apps. However, I am encountering an iss ...

The power of Ionic 2 combined with the Web Audio API

I am currently developing an Ionic 2 application that requires access to the user's microphone. When working on a web platform, I would typically use the following code snippet to obtain microphone access. navigator.getUserMedia = (navigator['ge ...

Incorporating a prop in keyframe animation with styled components

How should props be properly used within animations: ${styledKeyFrame} ${props.myProps}? The problem: import styled from 'styled-components'; const KeyFrameTest = styled.keyframes` from { opacity: 0; } to { opacity: 1; } `; const Style ...

Signing out of Firebase Authentication - using Node.js

Currently, I am utilizing Firebase for user management. The method firebase.auth().signInWithEmailAndPassword() is used for user sign-in and it operates smoothly. However, when attempting to sign out with the firebase.auth().signOut() method, it triggers a ...

Tips for adding values to an object

Behold, a complex object in multiple dimensions: let b = {} b.push({hello:'xyz'}) This method is currently inactive ...

Tips for moving a polygon while dragging a marker within its boundaries

Currently, I have a map displaying polygons and markers, accompanied by a sidebar featuring tool buttons (similar to the setup showcased in this demo: ). Each marker on my map is connected to the respective polygon stored in my database. When I utilize the ...

Easy peasy add-to-cart functionality using AJAX

Hey everyone, I'm trying to figure out how to add items to a cart and display them on the page without having to reload the entire page. It's been challenging for me, so I decided to start with a simple example to understand the logic better. In ...

Load the specialized orchard widget in an asynchronous manner

I have developed a custom module by referencing several examples. My approach involves utilizing the ContentPartDriver inherited class to efficiently render the desired outcomes... Here's an example snippet of my code: protected override Dr ...

Is there a regular expression that can identify whether a string is included in a numbered list?

Struggling with creating a regular expression to determine if a string is part of a numbered list like those in word processors. Need it to return true only if the string starts with a number, followed by a full stop and a space. Easy for single or doubl ...

Issues with the HTML required attribute not functioning properly are encountered within the form when it is

I am encountering an issue with my modal form. When I click the button that has onclick="regpatient()", the required field validation works, but in the console, it shows that the data was submitted via POST due to my onclick function. How can I resolve thi ...

The Firebase Auth Multifactor feature does not include the multiFactor property in the user object

Looking to implement Multi-Factor Authentication (MFA) in my web app, but encountering an issue where the multiFactor property is missing in the code snippet below: import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.2/firebase-app.j ...

Building a versatile dropdown menu with ReactJS and creating reusable components

I am currently working on building a dropdown menu following a tutorial, but I have encountered a roadblock. Instead of using the "props" keyword as shown by the instructor in the tutorial, I passed the props directly as arguments without using props dot. ...

What are the steps for choosing the current date from a dynamic calendar using Selenium?

I am having an issue where the calendar display is showing dates from the current date to the next upcoming date. However, I need to select the current date every time I run the script. This is how the calendar looks like: I attempted to solve this issue ...

In Ember.js, where should I place the initialization code for a controller? I attempted to set it up in the routes

With my experience working with ember.js and highcharts, I have come across some examples that were too simplistic for me to grasp how to set up the chart objects and render them properly. I have explored initializers and understand the significance of ro ...

In production, all Next.js API routes consistently return an "Interval Server Error," whereas in development, all routes operate smoothly without any issues

Every time I access any API route in my Next.js application in production, it results in a 500 "Internal Server Error". However, in development mode, all routes function smoothly and provide the expected output. https://i.stack.imgur.com/nPpeV.png https: ...