to create more complex melodies and harmonics you can use a scale, which is a set of notes that go together. a scale might be D, F, G, G#, A, C, C#, and then back to D. if you're song is the D scale i just wrote, you can play around with those notes and it will mostly go together.
you have the right idea of scales but thats not quite accurate. you can't "write" your own scales. it is what it is. scales have already been defined by all our predecessors.
Im trying to think of what scale that might be, but none came to mind. you missed the E.
every scales hits every note on the musical alphabet ( A B C D E F G)
so a D scale starts on D, then goes to E, then F , G, A, B, C then hits that next D, then goes back down.
what determines exactly what kind of scale it is is whether the starting note is flat, sharp, or natural, and the sequence of intervals (musical distance [half step, whole step, 1 1/2 steps]) used for the rest of the notes.