I’m trying to create an MVC pattern in my android whack-a-mole game.
I’m generating mole locations in the model via an inner class thread and want to eventually pass it to the view so that it would generate a sprite for it.
how do I create a way for my view to continuously receive the generated mole locations from my model?
I’ve edited my code below to capture the essentials behind them.
MODEL :
public class GameModel{
public GameModel(){
spawner = new MoleSpawner();
spawner.start();
}
.
.
.
private class MoleSpawner extends Thread{
private int location;
public void run() {
location = new Random().nextInt(20);
try{
sleep (1000);
} catch (InterruptedException ex){
ex.printStackTrace();
}
}
}
}
VIEW:
public GameView{
.
.
.
public void createMoleSprite(int newlocation){
//create sprites here
//newlocation should come from the MODEL
//this method must be triggered everytime the MODEL creates a new location
}
}
One of the ways you can implement this is by using Handlers.
It can be more complex, but I’ll give you a simple example on how to implement this.
In the Activity where your game is running, get it’s Handler by using
Then, when you instantiate your model, pass it the mHandler object as well as a reference to your activity. In your model, whenever you need to spawn a new mole, do
This can become a lot more complex, expecially if you control the rate at which moles are spawned dynamically, but you can build on this.
You can find a good tutorial on Handlers HERE.