snakelet
snakelet copied to clipboard
Constrain snake in parent DIV?
Hello, thank you so much for this awesome script. It is possible to constrain the snake movement inside the parent DIV? Thank you so much!
I tried that once, but didn't get it to work properly - always had a problem that the widths & heights which were somewhat off...
But here's what I tried then:
- not creating a new div but selecting your own parent div:
//snake._el_container = document.createElement('div');
snake._el_container = document.getElementById('my-snake-div');
//document.body.appendChild(snake._el_container);
snake._el_container.style.overflow = "hidden";
- Also attaching the "food" target to my DIV, not the HTML body
//document = document.appendChild(target);
snake._el_container.appendChild(target)
- Then changing all "window." and height/width references to use my Div
//… = window.innerHeight
… = snake._el_container.clientHeight
//… = window.innerWidth
… = snake._el_container.clientWidth
Somewhat the calculations were off making the game not detect the Div element's border to detect correctly, and also the "food" targets where always placed in the top left...
Thank you so much for your kind feedback. I know HTML & CSS but not Javascript, so I need a simpler solution. ;) May I ask if there is a way to set a top and bottom margin to constrain the snake and food area in the page? Or to assign a z-index to have always the elements (snake and food) on top? Thank you so much!