Thank you for your advice! I was able to get it working exactly the way I wanted!
I found that a big problem was also that I was trying to decrement the energy all the time instead of once a second, so it was stuck constantly trying to do the loop which made it crash.