I'm a bit confused with the terms. I don't understand how a number of leading zeros, target and difficulty are related to each other. Also, I don't understand how the number of zero's are calculated for the next target.
The target is a number which the hash of a block header must be less than or equal to in order for that block to be considered valid. This target number, when represented as a 256 bit number, has several leading zeros. The actual number of leading zeros is irrelevant and doesn't matter to anything, but us humans talk about the number of leading zeros as a way to understand what mining is doing with the target. It is easier for people to understand that a hash must have some number of leading zeros which is specified by the target than it is for people to understand that the hash is a very large number, and the target is a very large number, and that the hash must be less than the target. Otherwise, the number of leading zeros is irrelevant. The number of leading zeros is based on the target.
The difficulty is also kind of irrelevant. It is just something for us humans to understand how much work is being done to mine blocks. The difficulty is an alternative representation of the target and is just the highest target value possible divided by the current target value.
Of these three things, only the target actually matters. That is what is used to determine if a hash is valid and that is what is changed every 2016 blocks. The number of leading zeros and the difficulty are just different representations of the target to make it easier for people to understand.
D = maxTarget/Target
Target is < maxTarget
In words, D divided be maxTarget is the inverse of the probability of a single hash being less than target. Difficulty = 1/probability but scaled down by maxTarget.
It appears maxTarget is used simply to scale D down from the range of billions of septillions (10^33) to the millions.
maxTarget is a 256 bit number (like Target) usually expressed in hex and begins with zeros and can be seen starting like this: 0007FFFF..... Each of these hex values is a nibble (half a byte) aka 4 bits. The 7 is a nibble like this: 0111. F = 1111. So this 0007FFF... number has 3x4+1 = 13 leading zeros when expressed as bits.
HashRate and D are related like this:
D = HR * T / 2^x
where T=target solvetime and x is the leading zeros.
The number of hashes needed for a 50% chance of finding a solution are:
Hashes = D * 2^x = (2^256-1) / target.
There is a pool D and a chain D that are slightly different:
pool_D = coin_D * 2^16 / (2^16 - 1)