Now let’s add in our infinite/forever loop to complete the program.
Add the code into your program as shown. Just like before, we need to constantly be getting the position of our player, so this is the first thing in our loop.
We then create two random numbers “rX” and “rZ” by using the “randint” function. The “randint” takes two parameters, here we use -20 and 20.
This function then picks a random number between those two numbers. So here, rX and rZ are both random numbers between -20 and 20.
This is very important because we want our anvils to spawn at random positions to make the game fun. If the anvils always spawned at the same position the game would be very easy and the player would get bored very quickly.
We then set an anvil block using these random numbers (y doesn’t need to be random, we’ll just have all the anvils start at the same height).
We then call time.sleep to give a brief delay in the program between anvil spawns. If we didn’t have this delay our program would try to spawn all our anvils at once, and our game would probably crash!
Now that all that has been completed, go ahead and test it out!
If done correctly, you should see anvils start falling from the sky around you! If not, go back and double check your code for any errors.
See how long you can survive in this game! Are there any things you can think of to either improve or add onto it?
Remember, to stop an infinite/forever loop go into the Terminal of Visual Studio Code and press Ctrl+C, you can also exit the world you are in.