I've been working on a project for uni, and while I'm familiar with HTML and CSS, my knowledge with js is very vague.
I'm trying right now to make some kind of gallery where you can navigate with keyboard arrows through images that sometimes branches in any of the 4 directions, think of it as a 'Choose Your Own Adventure' book, but I'm kind of stuck.
Like this, where every frame covers the whole screen and you navigate through it like the first answer here: but in any direction as long as there is another frame there.
See comments and links below!
It's ugly but worked solution, if you are novice, it may help you in your learning:
var coord = function (name, isPass,x,y) {
return {
name: name,
pass: isPass | false,
x:x,
y:y
}
}
var map = [
[
new coord("x:0,y:0", true,0,0),
new coord("x:1,y:0", true,1,0)
],
[
new coord("x:0,y:1", false,0,1),
new coord("x:1,y:1", true,1,1)
],
]
const notPossibleCoord = new coord("", false, -1, -1);
var currentPosition = new coord("", false, -1, -1);
function tryMove(direction) {
var nextDirection;
try {
switch (direction) {
case "top": nextDirection = map[currentPosition.x][currentPosition.y + 1]; break;
case "bottom": nextDirection = map[currentPosition.x][currentPosition.y - 1]; break;
case "left": nextDirection = map[currentPosition.x - 1][currentPosition.y]; break;
case "right": nextDirection = map[currentPosition.x + 1][currentPosition.y + 1]; break;
default:
return notPossibleCoord
}
if (nextDirection.pass)
return nextDirection;
else
return notPossibleCoord;
} catch (e) {
//index out of range, it's your edge
return notPossibleCoord;
}
}
function onArrowPress() {
var prevPosition = currentPosition;
currentPosition = tryMove("top");
if (currentPosition == notPossibleCoord)
return; //do nothing if movement not possible
//do what you need to do
}
Some comments:
not possible
(be care! it's need ES6(ES2015 may be), so, instead of const
you can use just var
;tryMove
- it's your main function for movementsdocument.keyPress
or something event our function onArrowPress
, check is it 'arrow' or not, and do your logicWhat you need to learn for understand that's all: