public void newCharacter(CharacterEvent ce) { int oldChar2type; // Previous character not typed correctly - 1 point penalty if (ce.source == generator.get()) { oldChar2type = char2type.getAndSet(ce.character); // 接收随机字母 if (oldChar2type != -1) { score.decrementAndGet(); setScore(); } } // If character is extraneous - 1 point penalty // If character does not match - 1 point penalty else if (ce.source == typist.get()) { // 在此有个假设:即正在使用的该变量值不会被变更且程序代码完成时也是如此 // 所有已经被我们设定的具有特定值的变量就应当是那个值。 while (true) { oldChar2type = char2type.get(); // 获取上次已接收到的随机字母 if (oldChar2type != ce.character) { // ce.character是用户输入的字母,现在作比较 score.decrementAndGet(); break; } else if (char2type.compareAndSet(oldChar2type, -1)) { score.incrementAndGet(); break; } } setScore(); } }
public void resetTypist(CharacterSource newTypist) { CharacterSource oldTypist; if (newTypist != null) newTypist.addCharacterListener(this); oldTypist = typist.getAndSet(newTypist); if (oldTypist != null) oldTypist.removeCharacterListener(this); }
public void resetGenerator(CharacterSource newGenerator) { /** 注意这个方法的算法更改逻辑 */ CharacterSource oldGenerator; if (newGenerator != null) newGenerator.addCharacterListener(this); oldGenerator = generator.getAndSet(newGenerator); if (oldGenerator != null) oldGenerator.removeCharacterListener(this); }