First, remember that we are talking about four different engine cycles here: Intake; Compression; Ignition/Combustion; Exhaust. Top dead center (TDC) happens between two of these cycles: between Compression and Combustion, then again between Exhaust and Intake. The reason the piston and valve do not come into contact is because either the piston is following the exhaust valve, or the intake valve is following the piston. When I say the "follows" the piston, or visa-versa, I mean to say as the piston comes up, the exhaust valve closes which does not allow for each of them to come into contact. When I say the intake valve follows the piston, it opens slowly enough for the piston to be out of the way before any contact happens. (NOTE: Slow is a relative term here ... think piston speed v. valve open/close speed.) The valve doesn't just open completely all at once, it gradually opens as it follows the cam lobe profile. Also, this doesn't mean that valves and pistons don't share the same space, they just do it during different times of the cycles. These types of motors are referred to interference motors. If a timing belt were to slip or break while the engine is running, catastrophic effects will occur, causing major engine damage (usually requiring complete engine replacement, but at a minimum can "just" require head work or replacement).
The explosion wouldn't be so good since there would still be ports open when the spark plug fires making poor compression?
For almost the entire cycles of compression and combustion, intake and exhaust valves are all closed, allowing for a complete sealing of the combustion area and helping to absorb all of the power which is available. Hopefully not confusing the issue, I will tell you that the intake valve remains open for a short time during the beginning of the compression cycle, as well as the exhaust valve opening before the piston gets to the bottom of the combustion cycle, but specifics of why this happens is probably best left for another writ.