【发布时间】:2017-05-25 04:16:37
【问题描述】:
我想要完成什么?
我试图让 TrumpHead 继续移动,直到按下另一个键将其移动到不同的方向,就像在游戏中的蛇一样。我能想到的唯一一件事是制作一堆案例,每个案例中都充满了案例?欢迎任何想法和需要帮助,JavaScript 新手。
我的代码
var width = 1000, height = 1000; //Width and Height of Canvas
var cvs = document.getElementById('Snake'); //cvs is representing Canvas
var ctx = cvs.getContext('2d'); //ctx is context represented in 2 dimentions.
cvs.width = window.innerWidth; //setting the canvas width to be the width above.
cvs.height = window.innerHeight; //setting the canvas height to be the height above.
var img = new Image();
img.src = 'snakeHead.png';
var TrumpHead = canvasImage(100, 100, img);
window.addEventListener('keydown',this.checkOn,false);
//window.addEventListener('keyUp',this.checkOff,false);
function canvasImage(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) {
//var pos = getTrumpPos();
//var x = pos [0];
//var y = pos [1];
//alert(e.keyCode);
switch (e.keyCode) {
case 37://left
if (TrumpHead.x == cvs.width) { //this is just alerting you lose if
you go off the canvas
alert("You Lose");
} else if (TrumpHead.x < 0) {
alert("You Lose");
} else {
LeftDirection ();
console.log("Pressed Left");
console.log(x,y);
}
break;
case 38: //up key
if (TrumpHead.y < 0) {
alert("You Lose");
} else if (TrumpHead.y > cvs.height) {
alert("You Lose");
} else {
console.log("Pressed Up");
UpDirection();
console.log(x,y);
}
break;
case 39: //right
if (TrumpHead.x > cvs.width) {
alert("You Lose");
} else if (TrumpHead.x < 0) {
alert("You Lose");
} else{
console.log("Pressed Right");
console.log(x,y);
RightDirection();
}
break;
case 40: //down
if (TrumpHead.y < 0) {
alert("You Lose");
} else if (TrumpHead.y > cvs.height) {
alert("You Lose");
} else{
console.log("Pressed Down");
console.log(x,y);
DownDirection(); //this is a function defined in the movementFunctions section.
}
break;
// default: alert(e.keyCode); //Everything else
}
}
function gameLoop()
{
// change position based on speed
checkOn();
setTimeout("gameLoop()",10);
}
function LeftDirection ()
{
TrumpHead.x = TrumpHead.x - 50;
ctx.clearRect(0,0,cvs.width,cvs.height); //clears the gamescreen
ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
//Puts Trump down.
}
function RightDirection ()
{
TrumpHead.x = TrumpHead.x + 50;
ctx.clearRect(0,0,cvs.width,cvs.height);
ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}
function UpDirection ()
{
TrumpHead.y = TrumpHead.y - 50;
ctx.clearRect(0,0,cvs.width,cvs.height);
ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}
function DownDirection () {
TrumpHead.y = TrumpHead.y + 50;
ctx.clearRect(0,0,cvs.width,cvs.height);
ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}
【问题讨论】:
-
尝试使用对象映射,switch case增加复杂度
-
@brk 谢谢,有没有学习对象映射的好地方?我对此很陌生。
标签: javascript function loops switch-statement