1

I'm making an Android whack a mole game. I have the main activity which is basically the launcher, when you press the Play button the game activity starts. This works fine as it shows the background image and all molehills but I don't know how to call the method to start the game. I've tried to call it from inside onCreate() but this ends up "playing the game" itself. I've tried to call it right after the startActivity(intent) but the app crashes. And also I've tried to create an instance of the game class and call the play() method after the start activity but it doesn't work aswell. I don't know how to start the game method once the game activity is loaded.

I hope I explained well, thank you.

public class MainActivity extends AppCompatActivity {
    ImageButton btnStart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Hide TitleBar
        try { this.getSupportActionBar().hide();}
        catch (NullPointerException e){}

        setContentView(R.layout.activity_main);

        btnStart = (ImageButton)findViewById(R.id.btnStart);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), GameView.class);
                startActivity(intent);
            }
        });
    }        

And this is the code for the game_activity

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Hide TitleBar
    try { this.getSupportActionBar().hide();}
    catch (NullPointerException e){}

    setContentView(R.layout.activity_game_view);

    game();
}

The game() method is a typical game loop.

public void game() {

    Random random = new Random();
    int index;

    /*
     * Casting array to store all ImageView on the game
     */
    imgViewArray[0] = (ImageView)findViewById(R.id.img1);
    imgViewArray[1] = (ImageView)findViewById(R.id.img2);
    imgViewArray[2] = (ImageView)findViewById(R.id.img3);
    imgViewArray[3] = (ImageView)findViewById(R.id.img4);
    imgViewArray[4] = (ImageView)findViewById(R.id.img5);
    imgViewArray[5] = (ImageView)findViewById(R.id.img6);
    imgViewArray[6] = (ImageView)findViewById(R.id.img7);
    imgViewArray[7] = (ImageView)findViewById(R.id.img8);
    imgViewArray[8] = (ImageView)findViewById(R.id.img9);
    imgViewArray[9] = (ImageView)findViewById(R.id.img10);

    int j=0;

    while (j < 10) {

        // Get a random image to animate
        index = random.nextInt(10);


        switch(index) {
            case 0: imgViewArray[0].setImageResource(images[6]);
                new java.util.Timer().schedule(
                        new java.util.TimerTask() {
                            @Override
                            public void run() {
                                imgViewArray[0].setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        imgViewArray[0].setImageResource(images[0]);
                                    }
                                });
                            }
                        },
                        300 // The code executes after 300ms
                );
                break;
David AK
  • 125
  • 1
  • 14

2 Answers2

0

I think you should put the game() call inside onResume().

Saurav Mir
  • 124
  • 1
  • 11
0

There are many ways to solve the problem:

  1. Using EventBus
    Send the start game Event from Main Activity and register for the Event in the Game activity.

    This is my favorite way to handle the problem. It's because the simplicity and prevent us from tightly coupled code. The major problem with using EventBus is we will lost in the sea of Event if there are too much Event in the the app.

    How to do: First, create the Event. This is just a simple class:

    public class StartGameEvent {
    }
    

    Second, register for the event in the game activity:

    public class GameActivity extends Activity {
    
       protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
    
         ...
         EventBus.getDefault().register(this);
       }
    
       protected void onDestroy() {
         super.onDestroy();
         EventBus.getDefault().unregister(this);
       }
    }
    

    Third, subscribe for the event:

    public class GameActivity extends Activity {
      ...
    
      @Subscribe
      public void onMessageEvent(StartGameEvent event) {
        game();
      }
    }
    

    Last, send the event from Main activity:

    EventBus.getDefault().post(new StartGameEvent());
    
  2. Using LocalBroadcastManager
    You need to create the message and broadcast it in from your Main activity:

    Intent intent = new Intent("playEvent");
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    

    Then, in the game activity, you need to register as receiver:

    @Override
    public void onCreate(Bundle savedInstanceState) {
      // register for the event
      LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
       new IntentFilter("playEvent"));
    }
    
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        game();
      }
    };
    
    @Override
    protected void onDestroy() {
      // Unregister here
      LocalBroadcastManager.getInstance(this)
                           .unregisterReceiver(mReceiver);
      super.onDestroy();
    }
    

    I slightly modifying the code from How to use LocalBroadcastManager? for your case.

  3. Using a static method in Game activity
    This is the simplest way but highly discouraged. Because we can't ensure the state of the activity. Do not use this in production code. This is for learning sake only.

    You can make the game() method as a static method like this:

    public class GameActivity extends Activity {
        ...
      public static void game() {
        // game logic.
      }
    }
    

    Then call the method when you want with:

    GameActivity.game();
    
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
  • I've tried all the solutions on the answers and when I get to see the game interface all moles are on the screen ready to be clicked or touched, but I don't see the animations, I've added the code for the game() method, I've a Java program to measure reaction times and the loop is pretty similar, but it doesn't work here :/ – David AK Dec 03 '17 at 17:19