Start by figuring out
what and
why - you need to know the scope of the project you're undertaking. If you can't say to yourself "I am going to code
this in order to accomplish
this" then you're not going to get anywhere; you need to have a clear mental image of what your finished product will look like before you can work towards it, and you likewise need to know what purpose it'll fulfil before you'll be
motivated to work towards it.
This is why most OS projects don't work out: their authors usually have absolutely
no idea where their goalposts are, let alone what'll happen when they reach them.
In terms of writing the actual code, don't overthink things too much. If you just plonk down the first bit of logic that comes to mind, then yes, you'll probably find yourself going back to re-write it later on... but it's often
much faster to figure out "the proper way to do it" by
coding something and seeing how it works (or doesn't work) than it is to try and plot out your full program logic within the confines of your head. Writing a rough draft is better than writing nothing at all, even if only because the next step will seem so much more obvious afterwards.
Avoid distractions. Lyrical music is a big one - most of my playlist consists of video game music, which is typically instrumental. Slow ambient pieces work well, the longer the better. Think "strategy games".
This sort of stuff.
If you find that you can't stop tabbing out to your browser or whatever (as I often do when I can't figure out a bit of bugged code), force yourself away by getting up and going for a walk. Sometimes you just need to disengage your mind and let it free wheel.