While Loop for game crashes browser

While Loop for game crashes browser
0.0 0

#1

Working on a game loop but it crashes the browser. My similar code works for C++ and Java but it’s not working for JavaScript. Does anyone have any suggestions on getting this to work properly?

var gameOver = false;
var character1 = {
	name: "c1",
	hp: 100,
	mp: 50,
}

var character2 = {
	name: "c2",
	hp: 100,
	mp: 50,
}
while (gameOver != true) {

	if (character1.hp <= 0 || character2.hp <= 0) {
		gameOver = true;
	}
}
``

#2

First, you need to describe what you are trying to accomplish with the code you posted.


#3

If this is the only code you have so far, the problem is you have nothing in your code which changes the original values of character1.hp or character2.hp, so the if statement always evaluates to false, so gameOver remains false forever and that is why the while loop goes on forever also.


#4

I do have code that changes the values, I’m just not posting all my source code here. A function is called (upon player input event) that handles the hitpoint decrementing (damage) and incrementing (heals) . The property of the javascript object is manipulated and it works, just not within my loop construct.


#5

OK, what I see is that you are trying to set up a loop that will run “forever” until something you want happens. The browser will see this as an infinite loop.

In other languages, this might be how it’s handled, but not in JS. You need to think asynchronously. When the points are subtracted, you need to run a function that checks the hit points.

JS already essentially runs an infinite loop waiting for asynchronous events (like player 1 attacking player 2). You don’t need to make your own infinite loop. Just create whatever event is going subtract the points and check there.