During my experiments with Android, I have created a Yahtzee application with shake detection.
In this post I will give you an overview of the application and show you how to implement shake detection.
I also provide the full source code and an APK file, so you could install the game on your phone.
Features
The application has the following features:
- 1-4 players
- Shake to roll
- Highscores stored in SQLite database
Shake detection
The dices can be rolled by either pressing a button or by shaking the phone. For shake detection you need to create a SensorEventListener to monitor the accelerometer:
this.sensorMgr = (SensorManager) context.getSystemService(Activity.SENSOR_SERVICE); List<Sensor> sensors = sensorMgr.getSensorList(Sensor.TYPE_ACCELEROMETER); if (sensors != null && sensors.size() > 0) { sensorMgr.registerListener(this, sensors.get(0), SensorManager.SENSOR_DELAY_GAME); }
Now you have to implement the onSensorChanged method to react on shaking:
@Override public void onSensorChanged(SensorEvent sensorEvent) { long curTime = SystemClock.uptimeMillis(); // Ignore events that have occurred too early to get better speed approximation. if ((curTime - lastUpdate) > 200) { long diffTime = (curTime - lastUpdate); lastUpdate = curTime;x = sensorEvent.values[SensorManager.DATA_X]; y = sensorEvent.values[SensorManager.DATA_Y]; z = sensorEvent.values[SensorManager.DATA_Z]; float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000; if (speed > SHAKE_THRESHOLD) { // Shake detected // TODO: react on shake } last_x = x; last_y = y; last_z = z;
} }
Installation
The download contains the full source code and the file bin/Yahtzee.apk. To install the game on your Android device, place the file on your SD card or phone memory and use the Apps Installer.