I am trying to write a simple snake game and I am learning JavaScript as I do so. I have a separate file for my Snake class that I want the main file to use. The problem is that I have declared several variables at the top of the class to use in my functions but they are a hit or miss.
function Snake() {
this.move_y = 0;
this.move_x = 0;
this.height = 50;
this.width = 50;
this.speed = 20;
this.moveRight = function() {
this.speed = 20;
console.log(this.move_x); //Outputs 0
this.move_x += this.speed;
console.log(this.speed); //Outputs 20
//document.getElementById("head").style.left = this.move_x + "px";
}
this.moveDown = function() {
this.speed = 20;
console.log(this.move_y); //Outputs "Undefined"
this.move_y += this.speed;
console.log(this.move_y); //Outputs "NaN"
//document.getElementById("head").style.top = this.move_y + "px";
}
}
var dangerNoodle = new Snake();
dangerNoodle.moveRight();
dangerNoodle.moveDown();
This is the file that I am using that utilizes the class:
"use strict";
var move_x = 0;
var speed_x = 0;
var repeat;
var snakeHead = document.getElementById("head");
var snake;
window.onload = setUp;
function setUp()
{
snake = new Snake();
snakeHead.style.width = snake.width + "px";
snakeHead.style.height = snake.height + "px";
document.onkeydown = move;
}
function move(e)
{
if (e.keyCode == 39)
{
clearInterval(repeat);
repeat = setInterval(snake.moveRight, 1000);
}
else if (e.keyCode == 40)
{
clearInterval(repeat);
repeat = setInterval(snake.moveDown, 1000);
}
}
Why is it that my move_x
variable works as intended but my move_y
variable does not?