Android Open Source - android-simlple-minefield Game Activity






From Project

Back to project page android-simlple-minefield.

License

The source code is released under:

Apache License

If you think the Android project android-simlple-minefield listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.trabo.minefield;
//ww w  .j a v a  2s .  co m
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.trabo.minefield.utils.AppContract;
import com.trabo.minefield.utils.AppUtils;

import java.util.List;

import static com.trabo.minefield.utils.AppContract.GameType;

/**
 * @author Andriy Petruk <andrii.petruk{at}gmail.com>
 * @date 23.06.14.
 */
public class GameActivity extends Activity {
    public static final String GAME_TYPE_KEY = "game_type";

    private static final int TIMER_REFRESH_PERIOD = 100;

    private ToggleButton mBombMarkingButton;
    private TextView mUnmarkedTextView;

    private MinefieldView mMinefieldView;
    private GameType mCurrentType;

    private TextView mTimerTextView;
    private long mStartTime;

    private boolean mIsVibrationEnabled = true;

    private Handler mTimerHandler = new Handler();
    private Runnable mTimerRunnable = new Runnable() {

        @Override
        public void run() {
            long time = System.currentTimeMillis() - mStartTime;
            mTimerTextView.setText(AppUtils.getTimeString(time));
            mTimerHandler.postDelayed(this, TIMER_REFRESH_PERIOD);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_activity);
        mMinefieldView = (MinefieldView) findViewById(R.id.minefield_view);
        mBombMarkingButton = (ToggleButton) findViewById(R.id.mark_bomb);
        mTimerTextView = (TextView) findViewById(R.id.timer_text);
        mUnmarkedTextView = (TextView) findViewById(R.id.current_unmarked);

        SharedPreferences settings = getSharedPreferences(AppContract.SETTINGS_PREFS, 0);
        mIsVibrationEnabled = settings.getBoolean(AppContract.VIBRATION_KEY, mIsVibrationEnabled);

        findViewById(R.id.restart_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reset();
                startGame();
            }
        });
        int type = getIntent().getIntExtra(GAME_TYPE_KEY, 0);
        mCurrentType = GameType.values()[type];


        startGame();
    }

    private void reset() {
        mTimerTextView.setText(String.format(AppContract.TIME_FORMAT, 0, 0, 0));
        mTimerHandler.removeCallbacks(mTimerRunnable);
    }

    private void startGame() {

        final MineModel mineModel = new MineModel(mCurrentType.getWidth(), mCurrentType.getHeight(), mCurrentType.getNumMines());

        final MinefieldAdapter adapter = new MinefieldAdapter(this, mineModel.getWidth(), mineModel.getHeight(), new CellOnTouchListener() {
            @Override
            public boolean onClick(Point cell, View v) {

                if (mBombMarkingButton.isChecked()) {
                    mineModel.markFlag(cell);
                } else {
                    mineModel.hitCell(cell);
                }
                return true;
            }

            @Override
            public boolean onLongClick(Point cell, View view) {
                mineModel.highlightCell(cell);
                return false;
            }
        });

        mMinefieldView.setAdapter(adapter);
        mUnmarkedTextView.setText(String.format(AppContract.UNMARKED_FORMAT, mineModel.getCurrentUnmarked()));

        mineModel.setListener(new MineFieldListener() {

            @Override
            public void onStartGame() {
                mStartTime = System.currentTimeMillis();
                mTimerHandler.post(mTimerRunnable);
            }

            @Override
            public void onOpenCell(Point cell, int value) {
                vibrate(getResources().getInteger(R.integer.vibration_time_open));
                adapter.openCell(cell, value == 0 ? "" : String.valueOf(value));
            }

            @Override
            public void onOpenCells(Point[] cells, int[] values) {
                vibrate(getResources().getInteger(R.integer.vibration_time_open));
                for (int i = 0; i < cells.length; i++) {
                    adapter.openCell(cells[i], values[i] == 0 ? "" : String.valueOf(values[i]));
                }
            }

            @Override
            public void onHighLightCells(Point[] points) {
                adapter.highlightCells(points);
            }

            @Override
            public void onMarkCell(Point cell, int currentUnmarked) {
                vibrate(getResources().getInteger(R.integer.vibration_time_mark));
                mUnmarkedTextView.setText(String.format(AppContract.UNMARKED_FORMAT, currentUnmarked));
                adapter.markCell(cell);
            }

            @Override
            public void onUnMarkCell(Point cell, int currentUnmarked) {
                vibrate(getResources().getInteger(R.integer.vibration_time_mark));
                mUnmarkedTextView.setText(String.format(AppContract.UNMARKED_FORMAT, currentUnmarked));
                adapter.unMarkCell(cell);
            }

            @Override
            public void onLoseGame(List<Point> bombCells) {
                mTimerHandler.removeCallbacks(mTimerRunnable);
                vibrate(getResources().getInteger(R.integer.vibration_time_end));
                new AlertDialog.Builder(GameActivity.this).setMessage(R.string.lost_message).create().show();
                for (Point bombCell : bombCells) {
                    adapter.openBomb(bombCell);
                }
            }

            @Override
            public void onWinGame(List<Point> bombCells) {
                mTimerHandler.removeCallbacks(mTimerRunnable);
                vibrate(getResources().getInteger(R.integer.vibration_time_end));
                long time = System.currentTimeMillis() - mStartTime;
                new AlertDialog.Builder(GameActivity.this).setMessage(getResources().getString(R.string.won_message) + AppUtils.getTimeString(time)).create().show();
                for (Point bombCell : bombCells) {
                    adapter.openBomb(bombCell);
                }
                saveHighScore(time, mCurrentType);
            }
        });
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                mBombMarkingButton.setChecked(true);
            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                mBombMarkingButton.setChecked(false);
            }
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    private void vibrate(long milliseconds) {
        if (mIsVibrationEnabled) {
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(milliseconds);
        }
    }

    private void saveHighScore(long time, GameType gameType) {
        SharedPreferences settings = getSharedPreferences(AppContract.HIGH_SCORE_PREFS, 0);
        long currentHighScore = settings.getLong(gameType.name(), time);
        if (time <= currentHighScore) {
            SharedPreferences.Editor editor = settings.edit();
            editor.putLong(gameType.name(), time);
            editor.commit();
        }
    }
}




Java Source Code List

com.trabo.minefield.CellOnTouchListener.java
com.trabo.minefield.GameActivity.java
com.trabo.minefield.HighScoresActivity.java
com.trabo.minefield.MainActivity.java
com.trabo.minefield.MineFieldListener.java
com.trabo.minefield.MineModel.java
com.trabo.minefield.MinefieldAdapter.java
com.trabo.minefield.MinefieldView.java
com.trabo.minefield.utils.AppContract.java
com.trabo.minefield.utils.AppUtils.java
com.trabo.minefield.utils.MineGridUtils.java