snakelet icon indicating copy to clipboard operation
snakelet copied to clipboard

Constrain snake in parent DIV?

Open alessioscand opened this issue 4 years ago • 2 comments

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!

alessioscand avatar Oct 15 '21 15:10 alessioscand

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:

  1. 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";
  1. Also attaching the "food" target to my DIV, not the HTML body
//document = document.appendChild(target);
snake._el_container.appendChild(target)
  1. 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...

oliveratgithub avatar Oct 16 '21 07:10 oliveratgithub

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!

alessioscand avatar Oct 18 '21 11:10 alessioscand