Have you read the book of "The inner game of tennis"? Just like tennis, to be a top coder requires learning, practice, more learning and more practice. The mentality of a top coder often requires managements. When you are in the right mode, everything is in slow motion, your keyboard, your editing window, your debugging window all open, you know exactly what unit tests to write, when a bug comes out, you know exactly what to look for. You have a clear picture of what the end product should look like, how it is going to function, when each button is clicked, what is going to happen, when something went wrong, what will be the error message. All these are crystal clear in your mind, the boundary between you, your computer and your code disappears.
How to achieve such kind of mental status? The first step is to eliminating distractions. a. Make sure that you sit at a comfortable desk, the seating is ergonomic, there are right amount of light, b. make sure yourself is cleaned, well fed, hydrated and maybe even after some moderate amount of exercise c. close all the irrelevant windows on the computer. All those windows that are opened are related to the project that you want to work on.
The second step is to improve the focus by planning. This includes articulating the core scenario and algorithm, design the core test cases and write the spec. What is the primary scenarios that we want to enable for this? What is the core algorithm of the core scenario? Then you can start prototyping the core algorithm. Afterwards, you may want to design the core test cases for the core scenarios, particularly if you are into the test driven development (TDD). In the meanwhile, you can start drafting a design spec to document the core design decisions, such as selection of the framework that you are using, the pros and cons of the alternative designs, etc. All these prototype, core test cases, design spec will help you piece all these information together into your mind. With these planning efforts, you will be in a good shape of winning the inner game of coding.