Four rules, decided by the next letter
It is not three rules choosing among themselves: one main line plus one exception — only e / i change the g; everything else (including consonants) keeps it hard.
Each row shows how many example words this page records and how many turn up in our corpus — the corpus is small, so the examples are recorded separately (click a word to hear it).
Not e / i — a / o / u, or a consonant such as l / r. The tongue root closes against the soft palate: one normal release.
Before e / i (front vowels) the tongue root cannot reach the palate, so the blade squeezes up and the air rubs through — the same sound as the letter j.
The u exists only to keep the g hard, and is silent: guerra is [ˈgera], not [ˈgwera].
The two dots mark the only case where the u is pronounced: pingüino is [piŋˈgwino].
Why this happens
e / i are front vowels: they drag the tongue root forward
A [g] needs the tongue root against the soft palate, far back. With e / i the tongue sits forward, the root cannot reach the palate, and only a narrow gap remains — air rubs through it and you get [x]. This is coarticulation, not an exception.
So ge / gi and je / ji sound identical
In Spanish gente and jefe begin with the same [x]. Different letters, same sound — which is where the spelling rule below comes from.
What the u does: it keeps e / i away
The u in guerra is silent; it only sits between g and e so the g stays hard. Only gü with two dots is a real u ([w]).
The consequence: g turns into j
Because ge/gi and je/ji are homophones, a [x] before a / o has to be written with j. This is the most common spelling slip in verb conjugation.
Three places Mandarin speakers slip
Reading ge / gi as a hard g
Seeing the letter g, you read it like the g in go: gente becomes [ˈgente]. In Spanish gente starts exactly like jefe, both [x].
Pronouncing the u in gue
guerra is [ˈgera], two syllables; [ˈgwera] adds a w that is not there. Only güe with two dots pronounces the u (pingüino).
Still bursting between vowels
The g in amigo does not burst; it is [ɣ], with the tongue leaving a gap. That belongs to phonetics and lives on the spirantisation page; here you only need to know it is not always equally hard.
The numbers on this page
Rules: all four are hard orthographic rules of Spanish (g + vowel, gu + vowel, gü + vowel, and the g / j split after [x]); none of them needs a measurement.
Examples: 21 words, every one recorded on its own (not cut from a sentence), so you hear the word itself without its neighbours.
Corpus count: our corpus contains only 12 words with g (ga/go/gu 11, ge/gi 1, gue/gui 0, güe/güi 0) — far too few to be a distribution. It is listed only to explain why the examples had to be recorded separately.