Is it possible to have a function that creates an object? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Is it possible to have a function that creates an object?

Hello, To learn JavaScript, I'm attempting to make a classic snake game, and I've been stumped at figuring out how to make the snake grow when it eats the food. From what I can tell, (I might be totally wrong, please correct me if I am) each time I eat the food, a new object needs to be created for another block of the tail. I have no idea how to make a function that creates a unique object every time it's run, and I've been trying to do it with an array. Unfortunately, when I try to do that, it still seems like it registers as one object. Here's my code: https://pastebin.com/SivFvXwH

27th Mar 2018, 11:12 PM
Ismail Hasan
Ismail Hasan - avatar
3 Answers
+ 1
an array wouldn't work? var snakeBits=[] function addPiece(){ snakeBits.push(new object()); } Something like that? I made a snake game, and I struggled with this piece for 2 days (refused to seek help, went insane instead lol) .. It was a rough 2 days http://leakyegg.website.tk/SNAKE.zip
28th Mar 2018, 12:00 AM
LordHill
LordHill - avatar
0
How would I make it so that the bits follow the head though?
28th Mar 2018, 12:41 AM
Ismail Hasan
Ismail Hasan - avatar
0
I'm not sure tbh.. I had to come up with a workaround. i ended up adding a vector array in my java snake game and added an x/y location each time I ate a food. my way didn't pause the body while the head moved forward one like normal snake tho, it added one onto the tail at the location of the food that was eaten to create it
28th Mar 2018, 12:49 AM
LordHill
LordHill - avatar