Skip to content

Commit

Permalink
Refactor collision to use EventManager and update affected classes
Browse files Browse the repository at this point in the history
  • Loading branch information
elliottwahl committed Dec 1, 2023
1 parent cd32539 commit 2c6a33d
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 75 deletions.
28 changes: 28 additions & 0 deletions core/src/com/mygdx/game/EventManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.mygdx.game;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

public class EventManager {
// a map storing lists of event handlers (consumers) for each EventType
// allows for registering multiple handlers per event
private static Map<EventTypes, List<Consumer<Object>>> listeners = new HashMap<>();

public static void subscribe(EventTypes eventType, Consumer<Object> listener) {
// add the listener to the list for the given eventType
// if no list exists for this eventType, create a new list first
listeners.computeIfAbsent(eventType, k -> new ArrayList<>()).add(listener);
}

public static void notify(EventTypes eventType, Object data) {
if (listeners.containsKey(eventType)) {
// iterate through and execute each listener associated with the eventType passing in the event data
for (Consumer<Object> listener : listeners.get(eventType)) {
listener.accept(data);
}
}
}
}
5 changes: 5 additions & 0 deletions core/src/com/mygdx/game/EventTypes.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.mygdx.game;

public enum EventTypes {
COLLISION;
}
39 changes: 10 additions & 29 deletions core/src/com/mygdx/game/GameScreen.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,20 @@
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter;
import com.badlogic.gdx.utils.ScreenUtils;

public class GameScreen implements Screen {
private Game game;
private OrthographicCamera camera;
private SpriteBatch batch;
private Player player;
private PipeManager pipeManager;
private BitmapFont scoreText;
private Score score;
private Background background;
private Game game;
private FreeTypeFontGenerator generator;
private FreeTypeFontParameter gameOverParameter;
private BitmapFont gameOverText;
private FreeTypeFontParameter restartParameter;
private BitmapFont restartText;
private Fonts fonts;
private SpriteBatch batch;

public GameScreen(Game game) {
this.game = game;
Expand All @@ -46,29 +42,17 @@ public void show () {
scoreText = new BitmapFont();
scoreText.setColor(0, 0, 0, 1f);

score = new Score(player);
score = new Score();
score.calculateScore();

background = new Background();
background.playMusic();

generator = new FreeTypeFontGenerator(Gdx.files.internal("SuperMario256.ttf"));

gameOverParameter = new FreeTypeFontParameter();
gameOverParameter.size = 72;
gameOverParameter.borderColor = Color.BLACK;
gameOverParameter.borderWidth = 3f;
fonts = new Fonts();

gameOverText = generator.generateFont(gameOverParameter);
gameOverText.setColor(1f, 0, 0, 1f);
gameOverText = fonts.createFont(72, 3, Color.RED);

restartParameter = new FreeTypeFontParameter();
restartParameter.size = 24;

restartText = generator.generateFont(restartParameter);
restartText.setColor(0, 0, 0, 1f);

generator.dispose();
restartText = fonts.createFont(24, 0, Color.BLACK);
}

@Override
Expand Down Expand Up @@ -97,12 +81,9 @@ public void render (float delta) {
if (Gdx.input.isButtonJustPressed(Input.Buttons.LEFT)) {
score.saveHighScore();

// restart the game by setting up a new game screen instance
// ensures all game elements are reset without leftover data
game.setScreen(new GameScreen(game));

// call dispose to clean up current screen's resources preventing memory leaks
this.dispose();
dispose();

return;
}
Expand Down Expand Up @@ -133,13 +114,13 @@ public void hide() {

@Override
public void dispose () {
batch.dispose();
player.dispose();
pipeManager.dispose();
background.dispose();
scoreText.dispose();
gameOverText.dispose();
restartText.dispose();
score.dispose();
fonts.dispose();
batch.dispose();
}
}
3 changes: 1 addition & 2 deletions core/src/com/mygdx/game/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
import com.badlogic.gdx.Game;

public class Main extends Game {
@Override
public void create() {
setScreen(new MainMenuScreen(this));
this.setScreen(new MainMenuScreen(this));
}
}
32 changes: 9 additions & 23 deletions core/src/com/mygdx/game/MainMenuScreen.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,18 @@
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter;

public class MainMenuScreen implements Screen {
private Game game;
private OrthographicCamera camera;
private SpriteBatch batch;
private Background background;
private Game game;
private Player player;
private boolean isTextureDown;
private float timer;
private FreeTypeFontGenerator generator;
private FreeTypeFontParameter titleParameter;
private BitmapFont titleText;
private BitmapFont startText;
private FreeTypeFontParameter startParameter;
private Fonts fonts;
private SpriteBatch batch;

public MainMenuScreen(Game game) {
this.game = game;
Expand All @@ -44,22 +40,11 @@ public void show() {

isTextureDown = true;

generator = new FreeTypeFontGenerator(Gdx.files.internal("SuperMario256.ttf"));

titleParameter = new FreeTypeFontParameter();
titleParameter.size = 60;
titleParameter.borderColor = Color.BLACK;
titleParameter.borderWidth = 3f;
fonts = new Fonts();

titleText = generator.generateFont(titleParameter);
titleText = fonts.createFont(60, 3, Color.WHITE);

startParameter = new FreeTypeFontParameter();
startParameter.size = 24;

startText = generator.generateFont(startParameter);
startText.setColor(0, 0, 0, 1f);

generator.dispose();
startText = fonts.createFont(24, 0, Color.BLACK);
}

@Override
Expand Down Expand Up @@ -102,7 +87,7 @@ public void render(float delta) {

game.setScreen(new GameScreen(game));

this.dispose();
dispose();

return;
}
Expand All @@ -126,10 +111,11 @@ public void hide() {

@Override
public void dispose() {
batch.dispose();
background.dispose();
player.dispose();
titleText.dispose();
startText.dispose();
fonts.dispose();
batch.dispose();
}
}
4 changes: 2 additions & 2 deletions core/src/com/mygdx/game/Pipe.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ public Pipe(float screenWidth, Texture pipeTexture) {
pipeRectangle.height = pipeSprite.getHeight();
}

public void movePipe(float deltaTime, boolean playerCollision) {
public void movePipe(float deltaTime, boolean collisionCheck) {
// calculate horizontal movement based on defined speed and frame time if collision is not detected
// move the pipeSprite and its rectangle leftwards to simulate player movement
if (!playerCollision) {
if (!collisionCheck) {
velocityX = moveSpeed * deltaTime;

pipeSprite.translateX(-velocityX);
Expand Down
20 changes: 12 additions & 8 deletions core/src/com/mygdx/game/PipeManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,14 @@
public class PipeManager {
private ArrayList<Pipe> pipes = new ArrayList<Pipe>();
private Texture pipeTexture;
private boolean playerCollision = false;
private boolean collisionCheck = false;
private float initialDelay = 1f;
private float spawnInterval = 2f;

public PipeManager() {
pipeTexture = new Texture(Gdx.files.internal("pipe.png"));

EventManager.subscribe(EventTypes.COLLISION, this::handleCollision);
}

public void spawn() {
Expand All @@ -23,21 +27,21 @@ public void spawn() {
Timer.schedule(new Timer.Task() {
@Override
public void run() {
if (!playerCollision) {
if (!collisionCheck) {
Pipe pipe = new Pipe(800f, pipeTexture);

pipes.add(pipe);
} else {
this.cancel();
}
}
}, 1f, 2f);
}, initialDelay, spawnInterval);
}

public void draw(SpriteBatch batch, float deltaTime) {
// iterate through each pipe updating their position and rendering them on the screen
for (Pipe p : pipes) {
p.movePipe(deltaTime, playerCollision);
p.movePipe(deltaTime, collisionCheck);
p.getPipeSprite().draw(batch);
}
}
Expand All @@ -56,12 +60,12 @@ public void remove() {
}
}

public ArrayList<Pipe> getPipes() {
return pipes;
private void handleCollision(Object data) {
collisionCheck = true;
}

public void setPlayerCollision(boolean playerCollision) {
this.playerCollision = playerCollision;
public ArrayList<Pipe> getPipes() {
return pipes;
}

public void dispose() {
Expand Down
8 changes: 4 additions & 4 deletions core/src/com/mygdx/game/Player.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,15 @@ public void flap(float deltaTime) {
// synchronize the playerRectangle's vertical position with the updated playerSprite position for accurate collision detection
playerRectangle.y = playerSprite.getY();

collisionCheck();
handleCollision();
}

public void collisionCheck() {
public void handleCollision() {
// check for collision with the ceiling
if (playerSprite.getY() + 68f > 600f) {
canFlap = false;

pipeManager.setPlayerCollision(true);
EventManager.notify(EventTypes.COLLISION, null);

playerSprite.setY(600f - 68f);
playerSprite.setTexture(playerTextureDown);
Expand All @@ -86,7 +86,7 @@ public void collisionCheck() {
if (playerRectangle.overlaps(pipe.getPipeRectangle())) {
canFlap = false;

pipeManager.setPlayerCollision(true);
EventManager.notify(EventTypes.COLLISION, null);

playerSprite.setTexture(playerTextureDown);
}
Expand Down
27 changes: 20 additions & 7 deletions core/src/com/mygdx/game/Score.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,22 @@
public class Score {
private int score;
private int highScore;
private Player player;
private Preferences prefs = Gdx.app.getPreferences("prefs");
private boolean collisionCheck = false;

public Score(Player player) {
this.player = player;

public Score() {
// get the highest score from prefs defaulting to 0 if nothing is found
highScore = prefs.getInteger("highScore", 0);

EventManager.subscribe(EventTypes.COLLISION, this::handleCollision);
}

public void calculateScore() {
// increment score by 1 every second as long as player collision is not detected
Timer.schedule(new Timer.Task() {
@Override
public void run() {
if (player.getCanFlap()) {
if (!collisionCheck) {
score++;
} else {
this.cancel();
Expand All @@ -43,6 +43,19 @@ public void saveHighScore() {
}
}

// returns an integer (1-5) based on the score to determine the amount of difficulty scaling
public int scalingAmount() {
if (score > 25) {
return Math.min((score - 1) / 25, 5);
}

return 0;
}

private void handleCollision(Object data) {
collisionCheck = true;
}

public int getScore() {
return score;
}
Expand All @@ -51,7 +64,7 @@ public int getHighScore() {
return highScore;
}

public void dispose() {
player.dispose();
public int getScalingAmount() {
return scalingAmount();
}
}

0 comments on commit 2c6a33d

Please sign in to comment.