What is the goal of my task?
My objective is to keep the movement of the TrumpHead going until another key is pressed to change its direction, similar to the game snake. I am considering creating multiple cases with functions containing cases within each one. Any suggestions or assistance would be greatly appreciated as I am new to Javascript.
Here is my current code
var width = 1000, height = 1000; // Defining Canvas Width and Height
var cvs = document.getElementById('Snake'); // Representing the Canvas
var ctx = cvs.getContext('2d'); // 2D Context
cvs.width = window.innerWidth; // Setting canvas width to match window
cvs.height = window.innerHeight; // Setting canvas height to match window
var img = new Image();
img.src = 'snakeHead.png';
var TrumpHead = createCanvasImage(100, 100, img);
window.addEventListener('keydown', this.checkOn, false);
function createCanvasImage(x, y, img) {
this.image = img;
this.x = x;
this.y = y;
this.width = img.width;
this.height = img.height;
return this;
}
function checkOn(e) {
switch (e.keyCode) {
case 37: // Left Key
if (TrumpHead.x == cvs.width) {
alert("You Lose");
} else if (TrumpHead.x < 0) {
alert("You Lose");
} else {
left();
console.log("Pressed Left");
}
break;
case 38: // Up Key
if (TrumpHead.y < 0) {
alert("You Lose");
} else if (TrumpHead.y > cvs.height) {
alert("You Lose");
} else {
up();
console.log("Pressed Up");
}
break;
case 39: // Right Key
if (TrumpHead.x > cvs.width) {
alert("You Lose");
} else if (TrumpHead.x < 0) {
alert("You Lose");
} else {
right();
console.log("Pressed Right");
}
break;
case 40: // Down Key
if (TrumpHead.y < 0) {
alert("You Lose");
} else if (TrumpHead.y > cvs.height) {
alert("You Lose");
} else {
down();
console.log("Pressed Down");
}
break;
}
}
function gameLoop() {
checkOn();
setTimeout("gameLoop()", 10);
}
function left() {
TrumpHead.x = TrumpHead.x - 50;
ctx.clearRect(0, 0, cvs.width, cvs.height);
ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}
function right() {
TrumpHead.x = TrumpHead.x + 50;
ctx.clearRect(0, 0, cvs.width, cvs.height);
ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}
function up() {
TrumpHead.y = TrumpHead.y - 50;
ctx.clearRect(0, 0, cvs.width, cvs.height);
ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}
function down() {
TrumpHead.y = TrumpHead.y + 50;
ctx.clearRect(0, 0, cvs.width, cvs.height);
ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}