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 ofGame
, 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.