Cleaner update routine by extracting logic into new methods

This commit is contained in:
Matt Low 2020-01-05 10:42:45 +04:00
parent ab94395eac
commit 37944fccd9

View File

@ -360,6 +360,60 @@ public class PlayState extends LevelState {
}
}
private void updateScatterTimer(float dt) {
if (scatter || scatterCount < 4) {
// only update scatter timer if we're currently in scatter or if we've yet to enter scatter 4 times
scatterChaseTimer -= dt;
if (scatterChaseTimer <= 0) {
scatter = !scatter;
scatterChaseTimer = scatter ? 7f : 20f;
if (scatter) {
scatterCount++;
}
}
}
}
private void updateFrightTimer(float dt) {
frightTimer -= dt;
if (frightTimer <= 0) {
for (Ghost ghost : ghosts) {
if (ghost.currentBehaviour instanceof ReturnToBase) continue;
ghost.caught = false;
ghost.currentBehaviour = ghost.chaseBehaviour;
}
}
}
private void updateSecondsSinceLastDot(float dt) {
secondsSinceLastDot += dt;
if (secondsSinceLastDot >= 4) {
// It's been 4 seconds since pacman last ate a dot, he's tryin' to avoid ghosts coming out!
// We'll get him...
for (int i = 1; i < 4; i++) {
Ghost ghost = ghosts[i];
if (ghost.inHouse) {
ghost.leaveHouse();
secondsSinceLastDot = 0;
break;
}
}
}
}
// Returns whether pacman has been caught
private boolean handleGhostCollision(Ghost ghost) {
if (ghost.onSameTile(pacman)) {
if (frightTimer > 0 && !ghost.caught) {
ghostCaught(ghost);
} else if (!(ghost.currentBehaviour instanceof ReturnToBase)) {
pacmanCaught();
return true;
}
}
return false;
}
@Override
public void update(float dt) {
if (paused) {
@ -374,54 +428,18 @@ public class PlayState extends LevelState {
switch (state) {
case PLAYING:
if (frightTimer <= 0) {
if (scatter || scatterCount < 4) {
scatterChaseTimer -= dt;
if (scatterChaseTimer <= 0) {
scatter = !scatter;
scatterChaseTimer = scatter ? 7f : 20f;
if (scatter) {
scatterCount++;
}
}
}
updateScatterTimer(dt);
} else {
frightTimer -= dt;
if (frightTimer <= 0) {
for (Ghost ghost : ghosts) {
if (ghost.currentBehaviour instanceof ReturnToBase) continue;
ghost.caught = false;
ghost.currentBehaviour = ghost.chaseBehaviour;
}
}
updateFrightTimer(dt);
}
secondsSinceLastDot += dt;
if (secondsSinceLastDot >= 4) {
// It's been 4 seconds since pacman last ate a dot, he's tryin' to avoid ghosts coming out!
// We'll get him...
for (int i = 1; i < 4; i++) {
Ghost ghost = ghosts[i];
if (ghost.inHouse) {
ghost.leaveHouse();
secondsSinceLastDot = 0;
break;
}
}
}
updateSecondsSinceLastDot(dt);
pacman.update(dt);
for (Ghost ghost : ghosts) {
ghost.update(dt);
if (ghost.onSameTile(pacman)) {
if (frightTimer > 0 && !ghost.caught) {
ghostCaught(ghost);
continue;
}
if (!(ghost.currentBehaviour instanceof ReturnToBase)) {
pacmanCaught();
return;
}
if (handleGhostCollision(ghost)) {
return;
}
}
break;