mercredi 14 juin 2023

Logic for events and listeners

I'm writing simple snake game on java and i should use own events and listeners for collisions and food consumption. I made a research and as for now i found that observer is the best pattern to implement this. So i have a problem with logic for separation of my project First i have a class to fire events

public class Thrower implements Subject{
    private final ArrayList<Observer> observers;
    Thrower(){
        observers = new ArrayList<Observer>();
    }

    @Override
    public void addListener(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeListener(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void fireFoodConsumption() {
        Event event = new Event(this);
        for(Observer observer : observers){
            observer.foodConsumption(event);
        }
    }

    @Override
    public void fireOwnCollision() {
        Event event = new Event(this);
        for(Observer observer : observers){
            observer.ownCollision(event);
        }
    }

    @Override
    public void fireWallCollision() {
        Event event = new Event(this);
        for(Observer observer: observers){
            observer.wallCollision(event);
        }
    }
}

Then i have this one

public class Catcher implements Observer{
    @Override
    public void foodConsumption(Event event) {

    }

    @Override
    public void wallCollision(Event event) {

    }

    @Override
    public void ownCollision(Event event) {

    }
}

Question is following: where my game logic should be, in Catcher class, or in another one and is it okay to use one interface(Observer) with many functions to present different events. Can somebody give a hint, or example of some codes like mine?

Aucun commentaire:

Enregistrer un commentaire