Moving Element with Javascript

I want ginger cat image to move 50px in the direction of the button click https://codepen.io/JimKi8/pen/YzMOQVp
Jim
CodePen
YzMOQVp
...
51 Replies
Jimster
JimsterOP8mo ago
and because its a maze i want the cat not to be able to go through the walls
glutonium
glutonium8mo ago
use can use position property use position absolute, position the cat on top left either with css or js everytime a button is clicked, for example if right button is clicked, get the current x position of the cat, this will return you the x position of the top left corner of the ing so u need to offset the value by half the image width to get the horizontal central point. then add 50 to the value set that as the left: ; property u would need to use some sort of box collision detection tbh, i would just use grid and set the cat image and bg image to whatever tile it's going to go to instead of ACTUALLY moving the img u won't have that transition but it's gonna be less painful and won't look too bad if u use grid, then u can also use bitmap to create maze
Jimster
JimsterOP8mo ago
can you give an example because I've done similar stuff but I can figure it out idk what bitmap is but how would i move the cat when it is as a background img?
glutonium
glutonium8mo ago
that's the neat part, u don't say the cat is on the 1st tile, u want to move it to the 2nd tile u remove the bg image of the cat from the 1st tile and add to the 2nd tile u get what m saying?
Jimster
JimsterOP8mo ago
yea but how do i do that?
glutonium
glutonium8mo ago
it's a 2d array of 1 and 0 or even other numbers but mostly 1 and 0 where 1 might mean wall 0 might mean empty tile you use that array to represent the board i just told u well first of all, don't worry about walls rn just make the cat move
Jimster
JimsterOP8mo ago
but i want to know where to move the cat
glutonium
glutonium8mo ago
whichever method u want to use the cat will move based on what btn has been clicked xD wdym so for example if the right button is clicked, u check which box is on the right of the current box
Jimster
JimsterOP8mo ago
is there any way i can see the near boxes to my current position?
glutonium
glutonium8mo ago
then u basically remove the inage from the current box and add to the box on the right now how to figure out what box in on the right left top bottom, that's a tricky part but u should be able to solve it I personally would use matrix method like your whole board is a 2d matrix
| box box wall wall |
| wall box wall wall |
| wall box box wall |
| box box wall wall |
| box box wall wall |
| wall box wall wall |
| wall box box wall |
| box box wall wall |
here u can use indexes to uniquly identify each box like we do in matrix
| (0,0) (0,1) (0,2) (0,3) |
| (1,0) (1,1) (1,2) (1,3) |
......
......
| (0,0) (0,1) (0,2) (0,3) |
| (1,0) (1,1) (1,2) (1,3) |
......
......
where 1st digit mean the row 2nd digit mean the col so when say your current box is (1,1) and u wanna know what box is on the right, u just increase the col digit --> (1,2) for left u decrease --> (1,0) for top u decrease row digit --> (0,1) for bottom --> (2,1) ya what I just explained
Jimster
JimsterOP8mo ago
so i should make a "map" of the maze with the matrix method?
glutonium
glutonium8mo ago
well, that would be a more flexible method instead of hardcoding with html and css cause then you can just make an array of such maps with just 1 and 0 / bitmap turn your static game into dynamic by adding different level or heck, u can even procedurally generate bitmap but that's a bit too hard xD
Jimster
JimsterOP8mo ago
my brain is going to explode right now the "map" would be like this?
const easyMaze = [[0,0],[0,1]]
const easyMaze = [[0,0],[0,1]]
...?
glutonium
glutonium8mo ago
the bitmap for your current maze would be as follows
const maze = [
[ 0,1,0,1,1,1,1,1,1,1 ],
[ 0,1,0,1,1,1,0,1,1,1 ],
[ 0,1,0,1,0,0,0,0,1,1 ],
[ 0,1,0,0,0,1,1,0,1,1 ],
[ 0,1,1,1,1,1,0,0,1,1 ],
[ 0,1,0,0,0,0,0,1,1,1 ],
[ 0,1,0,1,1,1,1,1,1,1 ],
[ 0,1,0,0,0,0,0,0,1,1 ],
[ 0,1,0,0,0,1,1,0,1,1 ],
[ 0,0,1,1,1,1,1,1,0,0 ],
]
const maze = [
[ 0,1,0,1,1,1,1,1,1,1 ],
[ 0,1,0,1,1,1,0,1,1,1 ],
[ 0,1,0,1,0,0,0,0,1,1 ],
[ 0,1,0,0,0,1,1,0,1,1 ],
[ 0,1,1,1,1,1,0,0,1,1 ],
[ 0,1,0,0,0,0,0,1,1,1 ],
[ 0,1,0,1,1,1,1,1,1,1 ],
[ 0,1,0,0,0,0,0,0,1,1 ],
[ 0,1,0,0,0,1,1,0,1,1 ],
[ 0,0,1,1,1,1,1,1,0,0 ],
]
where 0 = orange and 1 = brown box
No description
glutonium
glutonium8mo ago
☝️
Jimster
JimsterOP8mo ago
oh wow thank you
glutonium
glutonium8mo ago
now here for example u can use a nested loop to loop through the whole board for each bit u make a box and give it the defined color u can use the bitmap to keep track of current box and boxs near using the same index method and u can use the index method to check if a box next to the current box is a wall or not by checking if the value is 1 or not since 1 represents wall welcome
Jimster
JimsterOP8mo ago
I'll try it in like an hour and if I run into a problem I'll send a message here
glutonium
glutonium8mo ago
try to isolate each section of the code into a different function for example, your first function might be createBoard() the sole purpose of it is to loop through the bitmap and set up the boxs nothing else
Jimster
JimsterOP8mo ago
https://codepen.io/JimKi8/pen/YzMOQVp @glutonium can you check now? the cat moves perfectly but when i move it another cat appears in the starting position
Jim
CodePen
YzMOQVp
...
glutonium
glutonium8mo ago
the buttosn don't work
glutonium
glutonium8mo ago
glutonium
glutonium8mo ago
i realise your html doesnt even have a start button
Jimster
JimsterOP8mo ago
Ohh its because the image is as background you cant see it in code pen The timer starts when a button is clicked Csn I upload images in code pen? Idk
glutonium
glutonium8mo ago
upload the image on discord open the image from discord in browser
glutonium
glutonium8mo ago
No description
glutonium
glutonium8mo ago
then copy the link and use that as src=""
Jimster
JimsterOP8mo ago
Jimster
JimsterOP8mo ago
some of the imgs are not being showed but that's not a problem
glutonium
glutonium8mo ago
it's still the same
Jimster
JimsterOP8mo ago
Yeah idk I'll just describe it So when I move the cat in a box a new cat appears at the 0,0 position
glutonium
glutonium8mo ago
u need to make sure to remove the background image from the previous position as well
Jimster
JimsterOP8mo ago
Yea I've done that but the image only stays on the 0,0 Every other box removes the image except this one
Jochem
Jochem8mo ago
you never set previousCatBox to anything before clearing you should initialize it to the start position instead of null
glutonium
glutonium8mo ago
once u r done with the project lemme know i also made something similar to yours, I'll share my code so u can check it out
Jimster
JimsterOP8mo ago
yea go for it i finished the project and delivered it, i made 3 difficulties thank you for the answer, I delivered the project Thanks you guys
glutonium
glutonium8mo ago
k I'll share the code here I can't log in to codepen for spme reason I'll just send the code here
<div class="board"></div>
<div class="buttons">
<button class="left" data-dir="left">Left</button>
<button class="right" data-dir="right">Right</button>
<button class="top" data-dir="top">Top</button>
<button class="bottom" data-dir="bottom">Bottom</button>
</div>
<div class="board"></div>
<div class="buttons">
<button class="left" data-dir="left">Left</button>
<button class="right" data-dir="right">Right</button>
<button class="top" data-dir="top">Top</button>
<button class="bottom" data-dir="bottom">Bottom</button>
</div>
body{
min-height : 100vh;
margin: 0;
display: grid;
place-items: center;
background: #101010;
}

.board{
width: 60%;
aspect-ratio: 1;
background: black;
display: grid;
grid-template: repeat(10, 1fr) / repeat(10, 1fr);
gap: 1px;
}

.path{
background: orange;
}

.wall{
background: brown;
}

.curr{
background: cyan;
}

button{
border: solid 2px orange;
background: transparent;
color: orange;
font-size: 1.5em;
padding: 0.5rem 1rem;
border-radius: 1rem;
cursor: pointer;
}
body{
min-height : 100vh;
margin: 0;
display: grid;
place-items: center;
background: #101010;
}

.board{
width: 60%;
aspect-ratio: 1;
background: black;
display: grid;
grid-template: repeat(10, 1fr) / repeat(10, 1fr);
gap: 1px;
}

.path{
background: orange;
}

.wall{
background: brown;
}

.curr{
background: cyan;
}

button{
border: solid 2px orange;
background: transparent;
color: orange;
font-size: 1.5em;
padding: 0.5rem 1rem;
border-radius: 1rem;
cursor: pointer;
}
const maze = [
[ 0,0,0,1,1,1,1,1,1,1 ],
[ 0,1,0,1,1,1,0,1,1,1 ],
[ 0,1,0,1,0,0,0,0,1,1 ],
[ 0,1,0,0,0,1,1,0,1,1 ],
[ 0,1,1,1,1,1,0,0,1,1 ],
[ 0,1,0,0,0,0,0,1,1,1 ],
[ 0,1,0,1,1,1,1,1,1,1 ],
[ 0,1,0,1,0,0,0,0,1,1 ],
[ 0,1,0,0,0,1,1,0,1,1 ],
[ 0,2,1,1,1,1,1,0,0,0 ],
];

const currIdx = { // position index of the current box that's cyan
i: 0,
j: 0
};

const board = document.querySelector(".board");
const buttons = document.querySelectorAll("button");

function createBoard(){
for(let i=0; i<maze.length; i++){
for(let j=0; j<maze[i].length; j++){
const div = document.createElement("div");

if(maze[i][j] === 0)
div.classList.add("path");
else if(maze[i][j] === 1)
div.classList.add("wall");
else{
div.classList.add("curr","path");
currIdx.i = i;
currIdx.j = j;
}

div.setAttribute("data-pos", `${i},${j}`);
board.appendChild(div);
}
}
}
createBoard();

buttons.forEach(btn => {
btn.addEventListener("click", e => {
move(e.target.getAttribute("data-dir"));
})
})

function move(dir){
let {i, j} = currIdx;

switch(dir){
case "left":
j -= 1;
break;
case "right":
j += 1;
break;
case "top":
i -= 1;
break;
case "bottom":
i += 1;
break;
}

if(maze[i][j] === undefined || maze[i][j] === 1) return;
console.log(maze[i][j])
document.querySelector(".curr").classList.remove("curr");
document.querySelector(`[data-pos="${i},${j}"]`).classList.add("curr");
currIdx.i = i;
currIdx.j = j;
}
const maze = [
[ 0,0,0,1,1,1,1,1,1,1 ],
[ 0,1,0,1,1,1,0,1,1,1 ],
[ 0,1,0,1,0,0,0,0,1,1 ],
[ 0,1,0,0,0,1,1,0,1,1 ],
[ 0,1,1,1,1,1,0,0,1,1 ],
[ 0,1,0,0,0,0,0,1,1,1 ],
[ 0,1,0,1,1,1,1,1,1,1 ],
[ 0,1,0,1,0,0,0,0,1,1 ],
[ 0,1,0,0,0,1,1,0,1,1 ],
[ 0,2,1,1,1,1,1,0,0,0 ],
];

const currIdx = { // position index of the current box that's cyan
i: 0,
j: 0
};

const board = document.querySelector(".board");
const buttons = document.querySelectorAll("button");

function createBoard(){
for(let i=0; i<maze.length; i++){
for(let j=0; j<maze[i].length; j++){
const div = document.createElement("div");

if(maze[i][j] === 0)
div.classList.add("path");
else if(maze[i][j] === 1)
div.classList.add("wall");
else{
div.classList.add("curr","path");
currIdx.i = i;
currIdx.j = j;
}

div.setAttribute("data-pos", `${i},${j}`);
board.appendChild(div);
}
}
}
createBoard();

buttons.forEach(btn => {
btn.addEventListener("click", e => {
move(e.target.getAttribute("data-dir"));
})
})

function move(dir){
let {i, j} = currIdx;

switch(dir){
case "left":
j -= 1;
break;
case "right":
j += 1;
break;
case "top":
i -= 1;
break;
case "bottom":
i += 1;
break;
}

if(maze[i][j] === undefined || maze[i][j] === 1) return;
console.log(maze[i][j])
document.querySelector(".curr").classList.remove("curr");
document.querySelector(`[data-pos="${i},${j}"]`).classList.add("curr");
currIdx.i = i;
currIdx.j = j;
}
Jimster
JimsterOP8mo ago
your code is much more readable than mine, maybe it would be better to change the j with x and i with y to indicate the axis I don't understand this part of the code
No description
Jochem
Jochem8mo ago
line by line,
//check if the index is out of bounds, or if the index is 1 (representing a wall), and if so return, effectively not moving the piece
if(maze[i][j] === undefined || maze[i][j] === 1) return;
console.log(maze[i][j])
//find an element that has the .curr class (which probably shows the cat as a background image) and remove it.
document.querySelector(".curr").classList.remove("curr");
//select the element that has a data attribute that matches the current position index (so for i=2, j=4 has the attribute data-pos="2,4"), and add the 'curr' class
//the attribute is set with the line "div.setAttribute("data-pos", `${i},${j}`);" in the createBoard function
document.querySelector(`[data-pos="${i},${j}"]`).classList.add("curr");
//store the current position in the global variable
currIdx.i = i;
currIdx.j = j;
//check if the index is out of bounds, or if the index is 1 (representing a wall), and if so return, effectively not moving the piece
if(maze[i][j] === undefined || maze[i][j] === 1) return;
console.log(maze[i][j])
//find an element that has the .curr class (which probably shows the cat as a background image) and remove it.
document.querySelector(".curr").classList.remove("curr");
//select the element that has a data attribute that matches the current position index (so for i=2, j=4 has the attribute data-pos="2,4"), and add the 'curr' class
//the attribute is set with the line "div.setAttribute("data-pos", `${i},${j}`);" in the createBoard function
document.querySelector(`[data-pos="${i},${j}"]`).classList.add("curr");
//store the current position in the global variable
currIdx.i = i;
currIdx.j = j;
as for x/y vs i/j, that's probably what I'd do too, but there's an argument to be made that i and j are more often used as array accessors. They're also used in createBoard in the for loops, so it's consistent with those (though that has no programatical reason for being consistent)
glutonium
glutonium8mo ago
ya what jochem said document.querySelector(".curr") fetches the element that is currently where the cat is, before it is moved the next line fetches the box where the cat will be after we move it but in order to move, we remove the cat from the element with curr class by removing the class itself and we add it to the element where the cat will be
Jochem
Jochem8mo ago
good practice would probably to use an optional chaining operator on the querySelector(".curr"), just in case
glutonium
glutonium8mo ago
agree we can use the same index method to get the curr element, since our bitmap corresponds to the actual board as well
Jimster
JimsterOP8mo ago
thanks for the explanation ok now i understand exactly how this works but I would never do it by myself at least for now
glutonium
glutonium8mo ago
well dw, these r nothing pro level coding 😂 you just need a bit of practice. once you understand how to modularize and isolate parts of your code independent from one and another you'll start to write clean code as well but yah, all u need is practice
Jimster
JimsterOP8mo ago
the more i code the more i realize there are so much to learn...
Jochem
Jochem8mo ago
it's not just learn, but also practice. People often think coding is just something you study and then you're great at it, but there's so much of it that is just repetition and training, just like any other creative work people do
Jimster
JimsterOP8mo ago
yea that so true, you need to think in code, i think thats the tough part
Jochem
Jochem8mo ago
This is the tough part, the breaking down and modularizing
glutonium
glutonium8mo ago
that's true you need that problem solving mindset which is hard to achieve
Jochem
Jochem8mo ago
once you have that though, there's very few programming challenges you can't solve
Want results from more Discord servers?
Add your server