I am currently working on writing small game that is written in javascript, alot like “snake”. Part of it is that me showing grid and that grid needs to be updated often.
And one way for me to do that is using below function.
function loadImages(){
for(var i = 0;i<HEIGHT;i++){
for(var j = 0;j<WIDTH;j++){
if(grid[i][j] == -1){
document.write('<IMG SRC="wall.png" width="30">');
}
else if(grid[i][j] == 0){
document.write('<IMG SRC="empty.png" width="30">');
}
}
}
setTimeout( loadImages(), 50 );
}
Only problem is that when loadImages() function is called over and over, images are concatenated not, replacing.
So my questions is that is there a way to overwrite document, or clear?
P.S. “document.clear()” function doesn’t seems to be all that helpful.
Thank you
You could extend your
griddata structure and store both the state and the image element:Then you can change the images inside
loadImagesin a similar manner:By the way:
setTimeout(loadImages(), 50)callsloadImagesimmediately but you should pass the function instead, sosetTimeout(loadImages, 50).You can optimize this your
loadImagesfunction by storinggrid[i][j]in a temporary variable and only change the images’ source if the state has changed: