It looks like magic, but the trick behind the NES Zapper (and similar light guns) is surprisingly simple. The barrel houses a small light sensor, essentially a tiny photocell that behaves like a basic camera.
Here's the clever part: when you pull the trigger, the console doesn't check the screen at the exact instant you fired. Instead, it briefly blanks the whole screen and then flashes the target area for a fraction of a second. If the sensor is pointed at the bright flash, it registers light and the game counts a hit. If you're aiming at empty background, the sensor sees darkness and it's a miss.
Because this all happens faster than the human eye can notice, it feels like the game is reacting to your shot in real time. So the duck isn't "detected" by shape or color at all. The system is really just asking one question: is the gun pointed at a bright spot right now?