I'm new to JavaScript and I'm trying to create a game just like this in javascript: http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/. Except I'm not allowed to use the canvas element so the code I use doesn't seem to work. The problem I'm having is getting my mouse/food element to move to a random new position when the snake/slither element collides with the mouse/food element. I'm also generally not sure if my update() function is working and if it isn't I don't know why.
I've tried a lot of different ways to get the code to execute correctly; placing the update function in different places like window onload,in each arrow function, etc. I tried sourcing many other codes but all I can find is people who use the canvas element to create their game.
var snake = null;
var slither = document.querySelector("#snake > .snake");
var mouse = document.querySelector("#food > .mouse");
var body = document.getElementById("grass");
x = body.width / 2;
y = body.height / 2;
function init() {
snake = document.getElementById("snake");
snake.style.position = 'relative';
snake.style.left = '0px';
snake.style.top = '0px';
}
function getKeyAndMove(e) {
var key_code = e.which || e.keyCode;
switch (key_code) {
case 37: //left arrow key
moveLeft();
break;
case 38: //Up arrow key
moveUp();
break;
case 39: //right arrow key
moveRight();
break;
case 40: //down arrow key
moveDown();
break;
}
}
function moveLeft() {
snake.style.left = parseInt(snake.style.left) - 7 + 'px';
update();
}
function moveUp() {
snake.style.top = parseInt(snake.style.top) - 7 + 'px';
update();
}
function moveRight() {
snake.style.left = parseInt(snake.style.left) + 7 + 'px';
update();
}
function moveDown() {
snake.style.top = parseInt(snake.style.top) + 7 + 'px';
update();
}
window.onload = init;
var update = () => {
if (
mouse.x === slither.x || mouse.y === slither.y || mouse.y === slither.y && mouse.x === slither.x
) {
mouse.x = Math.floor((Math.random() * 30) + 1);
mouse.y = Math.floor((Math.random() * 30) + 1);
}
};
<body id="grass" onkeydown='getKeyAndMove(event)'>
<div id="snake">
<img class="snake" src="img/snek.png" alt="snake">
</div>
<div id="food">
<img class="mouse" src="img/mouse.png" alt="mouse">
</div>
<script type="text/javascript" src="myscript.js"></script>
</body>
I need answers only in JavaScript please because I haven't learned JQuery and all that yet. I think there could be a problem with my x and y values but I don't know how to set the position of the mouse to move to relative to the window like they do in the canvas element examples. I'm just confused, please help.