r/code • u/ItsSk1m • Dec 16 '21
Halp pls! Stuck In Infinite Loop - Alternatives?
Hi, So I'm fairly new to programming and am coding a fun little game on Code.org. In the game I want a sprite (santa) to glide across the screen throughout the entire game (just in a straight line). To do this I'm using a while loop so it loops the code whenever the sprite is in a certain position, The problem is, I want to use other functions that happen while this sprite is moving such as a present dropping from "santa". But, I cannot do this because I get an error saying I cant put functions inside a loop. Im using code.org so its not the same as real JavaScript so sorry if this is confusing. Here is the loop.
function dropPresent() {
// Drops The Present When Button Is Clicked
while (presentY != chimneyPos) {
setPosition("present", presentX, presentY=presentY + 1 ,30 ,30);
console.log("present dropped" + presentX);
}
}
function moveSanta() {
// Moving Santa Across The Screen
setPosition("santa", santaX = santaX + .01, 0, 170, 140);
setPosition("present", santaX, 65,20,20);
// Loops Santa Around To Beggining
if (santaX >= 320) {
santaX = -150;
}
}
while (santaX > 0 < 320) {
if (presentDrop == true) {
console.log("dropped");
}
if (santaX > 0 < 320) {
// Keeps Santa Moving
moveSanta();
} else
santaX = -150;
}
});
1
u/Ok-Plane-3631 Jan 20 '22
Code.org is annoying and not my favorite - I'm pretty sure you need a while loop and include both functions or an if/then loop but that would only work if you have a function that has a present dropping from santa at any given location
1
u/JaggedMetalOs Dec 16 '21
I'm not familiar with code.org, but looking at other examples on the site it looks like you need to put your "loop" code in a draw() function.
This function I guess gets called automatically every frame, acting as your main game loop. The thing about for/while loops is they finish all of their loops in a single frame, so instead of animating it just skips right to the end of the loop (or possibly gets stuck if the loop never ends).
This is the example I was looking at:
https://studio.code.org/projects/gamelab/SfM10HpEEpJG-Ppji_OrQ8lr3VLEP1WkkVVAipHufx0/view
Edit: Also there is a specific subreddit for code.org related questions /r/Codeorg so you'd probably get better answers there.