Spoilers all around, you have been warned!
This episode has a bit of a problem concerning how the loop starts.
Remember that each room resets to its original state when the doctor leaves it. It is a crucial plot point. (Since it is necessary to start the loop.)
One hypothesis (on which I am still uncertain) can really change the way you see it, so I'm going to list both sides:
1. The castle was crystal clear when The Doctor first came inside it
In this case, the first loop start is ... edgy at best: how does the inscription written by The Doctor stay? How do the skulls stay? How does the shovel appear in the hallway? Why does the reset allow these elements to stay in place?
The only way to allow it would be that the resets of the "initial states" of the rooms can be changed by The Doctor dying (his skull does remain in place). Or that the small objects are not affected (why ?)
In this case, The Doctor, while dying the first time, thought of this solution to try again, with maybe small differences, and the loop converged on the loop we are seeing.
This explanation is a bit ... "try-to-make-things-worky" for my taste.
2. The loop is part of the hell
The castle is pretty much a purgatory for The Doctor. Since, at the end of the loop, he remembers all of the others, the loop can be seen as part of the hell. A reason to make him give up. It also has the advantage of always keeping him alive (since killing him is not the point).
In this version: the loop was designed as well as the castle.
My preference goes for the second explanation. But I have no in universe reason to favor one over the other.