I tend to write my best stuff when I am in a good mood. I get into a goofy kind of mode. I mumble to myself, make smart-ass remarks for no apparant reason (feel pity for my co-workers). In this mindset I am more open to creative and weird ideas. I can do lots of brain storming and I look at problems from a different perspective. I actually want to find the slickest way to solve the problem.
When I am in a bad mood I find it hard to concentrate on a problem. I get part way through and I forget where I was heading. At these times I am usually more interested in just getting it over with than coming up with something creative.
To keep myself in a good mood I will listen to a little music or talk to someone about things that have absolutely nothing to with programming. I try to do small projects rather than large ones. Scratching many items off my 'to do' can feel good and it's easier to fix up small projects when I'm in a better mood.
Being able to focus on other things for short periods of time is the key to maintaining my good mood.
I must completely agree with mr.greywolf on this one. I think music in the workplace completely eases the mind and allows me to focus on what I am working with at the time. I also believe I am more productive when I am talking nonsense with my co-workers.