I've been writing code for nearly ten years. I'm still pretty slow, and I still have trouble writing code for more than three hours at a time (unless I get really motivated). The one thing I have learned in my years of writing code is how to get the best out of my productivity.
Many studies have shown that your mind is at its best in the morning. While I fought this tooth and nail at first (I'm naturally a night owl), I realized that this was true when it comes to writing code. I always tackle the toughest coding puzzles first thing, and save the easier ones for later in the day.
Again, there are many studies to back up the validity of taking breaks. I'm here to tell you that it is essential! I like to set milestones for myself when working through a coding problem. An example mental milestone.
Get through the styling for desktop viewport and ipad landscape, test it, then take a break!
Sometimes breaks came in the form of getting up to go to the bathroom, get a cup of coffee, or go for a walk. As long as it involved not being in front of a computer screen and sitting down, I considered it a welcomed break.
Making a todo list
I like to feel accomplished at the end of a day. If I don't have a set of to-dos completed, I may as well have played Battlefield all day (which would be awesome, but not exactly productive). I use teuxdeux to write a ton of mini tasks.
In addition to feeling accomplished at the end of a work day, this process of writing granular to-dos is practice for writing good project estimates.
After I solve a really tough coding problem, I usually let out a big "F### YEAH!". Which as you could imagine, did not go over well in an open floor plan environment. Reeling in my enthusiam became a regular exercise for me at Vodori due to the environment. So I had to come up with ways to reward myself that didn't involve loud expletives.
When I conquered a tough problem, I would tell myself that I'm going to get something delicious for lunch. Or that I'm getting a beer after work. Or I would allow myself an hour or two of xbox one (again, Battlefield FTW!). The ritual of giving myself something to look forward to has really worked for me, and I think it will work for you too!