Does a basic melody have to be played around a certain root-key in order to follow music theory properly! Is this just basically staying within the same octave possibly or does it follow some other rule?
Theory describes. It does not command.
Much music centres on a home note, a home chord as well perhaps. It allows a journey away from that note and a return to it. You seem to be noticing how this works. Good!
What you’re asking about is tonality, and this is the way most western music has been thought for hundreds of years. In tonal music, the scale degrees, and the chords built on them, have a hierarchy. The root-key, or tonic, is the principle degree, and is “home” harmonically. All the other harmonies and pitches are thought of in how they relate to the tonic, e.g. how strongly they want to lead to the tonic, how similar they are to the tonic. This is a very useful and satisfying theory, since it allows a composer to set up a lot of anticipation, tension, and surprise in where harmonies lead. Basically, it helps create some overall coherence.
But there are also atonal systems, most notably in the 12 tone technique of the early 20th century. This system completely does away with any hierarchy, and notes are related to their neighbors and not a key. And before tonality, music in Europe was modal, which is based on different sets of scales and their roots, but still not a single home key. If you have a main melody that’s not really “in” what you think the root-key is, it might not be in a key at all.