Android Apps Development for Mobile Game Lesson 5

Similar documents
1. Location Services. 1.1 GPS Location. 1. Create the Android application with the following attributes. Application Name: MyLocation

ELET4133: Embedded Systems. Topic 15 Sensors

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 2


Xin Pan. CSCI Fall

Topics Related. SensorManager & Sensor SensorEvent & SensorEventListener Filtering Sensor Values Example applications

MAD ASSIGNMENT NO 2. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

Create Parent Activity and pass its information to Child Activity using Intents.

Tip Calculator. xmlns:tools=" android:layout_width="match_parent"

Sensor & SensorManager SensorEvent & SensorEventListener Filtering sensor values Example applications

API Guide for Gesture Recognition Engine. Version 2.0

Mobile Programming Lecture 9. Bound Services, Location, Sensors, IntentFilter

Android - JSON Parser Tutorial

Android Apps Development for Mobile Game Lesson Create a simple paint brush that allows user to draw something (Page 11 13)

public AnimLayer(Context context, AttributeSet attrs, int defstyle) { super(context, attrs, defstyle); initlayer(); }

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Managing Screen Orientation

Q.1 Explain the dialog and also explain the Demonstrate working dialog in android.

Android Application Development. By : Shibaji Debnath

Workshop. 1. Create a simple Intent (Page 1 2) Launch a Camera for Photo Taking

PENGEMBANGAN APLIKASI PERANGKAT BERGERAK (MOBILE)

API Guide for Gesture Recognition Engine. Version 1.1

Android Programs Day 5

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 4. Workshop

Mobile Application Development Lab [] Simple Android Application for Native Calculator. To develop a Simple Android Application for Native Calculator.

App Development for Smart Devices. Lec #8: Android Sensors

MAD ASSIGNMENT NO 3. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

Fragment Example Create the following files and test the application on emulator or device.

Press project on the left toolbar if it doesn t show an overview of the app yet.

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Vienos veiklos būsena. Theory

Time Picker trong Android

Upcoming Assignments Quiz today Web Ad due Monday, February 22 Lab 5 due Wednesday, February 24 Alpha Version due Friday, February 26

filled by the user and display it by setting the value of view elements. Uses display.xml as layout file to display the result.

Spring Lecture 9 Lecturer: Omid Jafarinezhad

Basic GUI elements - exercises

Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Cloudant NoSQL DB)

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

Mobile Health Sensing with Smart Phones

SD Module-1 Android Dvelopment

EMBEDDED SYSTEMS PROGRAMMING UI Specification: Approaches

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Mobile Software Development for Android - I397

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Switching UIs

StoppUhr. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="start1"

Intents. Your first app assignment

Database Development In Android Applications

Tutorial: Setup for Android Development

TextView Control. EditText Control. TextView Attributes. android:id - This is the ID which uniquely identifies the control.

Fragments. Lecture 11

1. Simple List. 1.1 Simple List using simple_list_item_1

Mobile Application (Design and) Development

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Designing Apps Using The WebView Control

Mobila applikationer och trådlösa nät

EMBEDDED SYSTEMS PROGRAMMING Android Services

LifeStreet Media Android Publisher SDK Integration Guide

Sensors. Marco Ronchetti Università degli Studi di Trento

<uses-permission android:name="android.permission.internet"/>

Our First Android Application

CSE 660 Lab 3 Khoi Pham Thanh Ho April 19 th, 2015

ANDROID (4) 2D Graphics and Animation, Handling Screen Rotation. Marek Piasecki

Custom Views in Android Tutorial

Android - Widgets Tutorial

Create a local SQL database hosting a CUSTOMER table. Each customer includes [id, name, phone]. Do the work inside Threads and Asynctasks.

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

Tutorial: Setup for Android Development

An Overview of the Android Programming

PROGRAMMING APPLICATIONS DECLARATIVE GUIS

INTRODUCTION TO ANDROID

Produced by. Mobile Application Development. Eamonn de Leastar

ANDROID PROGRAMS DAY 3

Learning Android Canvas

Software Practice 3 Before we start Today s lecture Today s Task Team organization


Working with Sensors & Internet of Things

Introduction to Android Development

Android Help. Section 8. Eric Xiao

CS 234/334 Lab 1: Android Jump Start

Have a development environment in 256 or 255 Be familiar with the application lifecycle

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

ITU- FAO- DOA- TRCSL. Training on. Innovation & Application Development for E- Agriculture. Shared Preferences

register/unregister for Intent to be activated if device is within a specific distance of of given lat/long

Programming of Mobile Services, Spring 2012

Group B: Assignment No 8. Title of Assignment: To verify the operating system name and version of Mobile devices.

Threads. Marco Ronchetti Università degli Studi di Trento

User Interface Development. CSE 5236: Mobile Application Development Instructor: Adam C. Champion Course Coordinator: Dr.

Adaptation of materials: dr Tomasz Xięski. Based on presentations made available by Victor Matos, Cleveland State University.

package import import import import import import import public class extends public void super new this class extends public super public void new

Exercise 1: First Android App

05. RecyclerView and Styles

android:layout_margintop="5dp" > <EditText android:layout_width="210dp"

M.A.D ASSIGNMENT # 2 REHAN ASGHAR BSSE 15126

CE881: Mobile & Social Application Programming

Assignment 1. Start: 28 September 2015 End: 9 October Task Points Total 10

Tabel mysql. Kode di PHP. Config.php. Service.php

ABSTRACT. As technology improves, the world of mobile devices has been continuously

MVC Apps Basic Widget Lifecycle Logging Debugging Dialogs

android-espresso #androidespresso

Android Coding. Dr. J.P.E. Hodgson. August 23, Dr. J.P.E. Hodgson () Android Coding August 23, / 27

Transcription:

Workshop 1. Create a simple Environment Sensors (Page 1 6) Pressure Sensor Ambient Temperature Sensor Light Sensor Relative Humidity Sensor 2. Create a simple Position Sensors (Page 7 8) Proximity Sensor Geomagnetic Field Sensor 3. Create a simple Motion Sensors (Page 9 13) Rotation Vector Sensor Acceleration Sensor 4. By using GPS service, find out your location by emulator and your mobile (Page 14 23) Obtain the GPS Location Send Mock Location to AVD 5. Exercise: It s time for you to create a simple maze game using sensor. By using Canvas, Sensor, learnt from these lessons, create a simple maze game. 4T026-1-A @ Peter Lo 2015

1. Environment Sensors 1.1 Pressure Sensor 1. Create the Android application with the following attributes. Application Name: MySensor Project Name: Package Name: MySensor com.example.mysensor 2. Check the layout file activity_main.xml, ensure that the id for textview1 is existed. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="com.example.mysensor.mainactivity" > <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout> 3. Modify the source file "MainActivity.java" as follow: package com.example.mysensor; import android.app.activity; import android.os.bundle; import android.view.menu; import android.content.context; import android.widget.textview; import android.hardware.sensor; import android.hardware.sensorevent; import android.hardware.sensoreventlistener; import android.hardware.sensormanager; 4T026-1-A @ Peter Lo 2015 1

public class MainActivity extends Activity implements SensorEventListener { private SensorManager msensormanager; private Sensor msensor; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // Get an instance of the sensor service, and use that to get an instance // of a particular sensor. msensormanager = (SensorManager) getsystemservice(context.sensor_service); msensor = msensormanager.getdefaultsensor(sensor.type_pressure); public void onsensorchanged(sensorevent event) { // Finds a view that was identified by the ID attribute from the XML TextView mtextview = (TextView) findviewbyid(r.id.textview1); // Display the value on screen mtextview.settext("pressure = " + event.values[0] + "hpa"); public void onaccuracychanged(sensor sensor, int accuracy) { public void onresume() { // Register a listener for the sensor super.onresume(); msensormanager.registerlistener(this, msensor, SensorManager.SENSOR_DELAY_NORMAL); public void onpause() { 4T026-1-A @ Peter Lo 2015 2

// Be sure to unregister the sensor when the activity pauses. super.onpause(); msensormanager.unregisterlistener(this); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; 4. Save and execute the app, you should able to obtain the pressure in your mobile (This app does not workable in emulator. Moreover, these sensors are hardware-based and are available only if a device manufacturer has built them into a device). 4T026-1-A @ Peter Lo 2015 3

1.2 Ambient Temperature Sensor 1. Open the previous project and modify the sensor type for the sensor manager to TYPE_AMBIENT_TEMPERATURE in source file "MainActivity.java". You can also update the text for displaying temperature. protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // Get an instance of the sensor service, and use that to get an instance // of a particular sensor. msensormanager = (SensorManager) getsystemservice(context.sensor_service); msensor = msensormanager.getdefaultsensor(sensor.type_ambient_temperature); public void onsensorchanged(sensorevent event) { // Finds a view that was identified by the ID attribute from the XML TextView mtextview = (TextView) findviewbyid(r.id.textview1); // Display the value on screen mtextview.settext("temperature = " + event.values[0] + "C"); 2. Save and execute the app, you should able to obtain the ambient air temperature in your mobile. 4T026-1-A @ Peter Lo 2015 4

1.3 Light Sensor 1. Open the previous project and modify the sensor type for the sensor manager to TYPE_LIGHT in source file "MainActivity.java". You can also update the text for displaying illuminance. protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // Get an instance of the sensor service, and use that to get an instance // of a particular sensor. msensormanager = (SensorManager) getsystemservice(context.sensor_service); msensor = msensormanager.getdefaultsensor(sensor.type_light); public void onsensorchanged(sensorevent event) { // Finds a view that was identified by the ID attribute from the XML TextView mtextview = (TextView) findviewbyid(r.id.textview1); // Display the value on screen mtextview.settext("illuminance = " + event.values[0] + "lx"); 2. Save and execute the app, you should able to obtain the illuminance in your mobile. 4T026-1-A @ Peter Lo 2015 5

1.4 Relative Humidity Sensor 1. Open the previous project and modify the sensor type for the sensor manager to TYPE_RELATIVE_HUMIDITY in source file "MainActivity.java". You can also update the text for displaying relative humidity. protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // Get an instance of the sensor service, and use that to get an instance // of a particular sensor. msensormanager = (SensorManager) getsystemservice(context.sensor_service); msensor = msensormanager.getdefaultsensor(sensor.type_relative_humidity); public void onsensorchanged(sensorevent event) { // Finds a view that was identified by the ID attribute from the XML TextView mtextview = (TextView) findviewbyid(r.id.textview1); // Display the value on screen mtextview.settext("relative humidity = " + event.values[0] + "%"); 2. Save and execute the app, you should able to obtain the ambient relative humidity in your mobile. 4T026-1-A @ Peter Lo 2015 6

2. Position Sensors 2.1 Proximity Sensor 1. Open the previous project and modify the sensor type for the sensor manager to TYPE_PROXIMITY in source file "MainActivity.java". You can also update the text for displaying distance. protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // Get an instance of the sensor service, and use that to get an instance // of a particular sensor. msensormanager = (SensorManager) getsystemservice(context.sensor_service); msensor = msensormanager.getdefaultsensor(sensor.type_proximity); public void onsensorchanged(sensorevent event) { // Finds a view that was identified by the ID attribute from the XML TextView mtextview = (TextView) findviewbyid(r.id.textview1); // Display the value on screen mtextview.settext("distance = " + event.values[0] + "cm"); 2. Save and execute the app, you should able to determine how far away an object is from a device. However, some proximity sensors such as Samsung S4 only provide binary values representing near and far. 4T026-1-A @ Peter Lo 2015 7

2.2 Geomagnetic Field Sensor 1. Open the previous project and modify the sensor type for the sensor manager to TYPE_MAGNETIC_FIELD in source file "MainActivity.java". You can also update the text for displaying geomagnetic field strength. protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // Get an instance of the sensor service, and use that to get an instance // of a particular sensor. msensormanager = (SensorManager) getsystemservice(context.sensor_service); msensor = msensormanager.getdefaultsensor(sensor.type_magnetic_field); public void onsensorchanged(sensorevent event) { // Finds a view that was identified by the ID attribute from the XML TextView mtextview = (TextView) findviewbyid(r.id.textview1); // Display the value on screen mtextview.settext("x axis = " + event.values[0] + "µt\n" + "y axis = " + event.values[1] + "µt\n" + "z axis = " + event.values[2] + "µt"); 2. Save and execute the app, you should able to obtain the geomagnetic field strength along the x, y, z axis from the mobile. 4T026-1-A @ Peter Lo 2015 8

3. Motion Sensors 3.1 Rotation Vector Sensor 1. Open the previous project and modify the sensor type to TYPE_ROTATION_VECTOR and the sensor change event as follow in source file "MainActivity.java". package com.example.mysensor; import android.app.activity; import android.os.bundle; import android.view.menu; import android.content.context; import android.widget.textview; import android.hardware.sensor; import android.hardware.sensorevent; import android.hardware.sensoreventlistener; import android.hardware.sensormanager; public class MainActivity extends Activity implements SensorEventListener { private SensorManager msensormanager; private Sensor msensor; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // Get an instance of the sensor service, and use that to get an instance // of a particular sensor. msensormanager = (SensorManager) getsystemservice(context.sensor_service); msensor = msensormanager.getdefaultsensor(sensor.type_rotation_vector); public void onsensorchanged(sensorevent event) { // Finds a view that was identified by the ID attribute from the XML TextView mtextview = (TextView) findviewbyid(r.id.textview1); // Display the value on screen 4T026-1-A @ Peter Lo 2015 9

if (event.values[0] < 0 && event.values[1] > 0) { mtextview.settext("top"); else if (event.values[0] > 0 && event.values[1] < 0) { mtextview.settext("down"); else if (event.values[0] < 0 && event.values[1] < 0) { mtextview.settext("left"); else if (event.values[0] > 0 && event.values[1] > 0) { mtextview.settext("right"); public void onaccuracychanged(sensor sensor, int accuracy) { public void onresume() { // Register a listener for the sensor super.onresume(); msensormanager.registerlistener(this, msensor, SensorManager.SENSOR_DELAY_NORMAL); public void onpause() { // Be sure to unregister the sensor when the activity pauses. super.onpause(); msensormanager.unregisterlistener(this); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; 4T026-1-A @ Peter Lo 2015 10

2. Save and execute the app, rotate your mobile to obtain the change. 3.2 Acceleration Sensor 1. Modify the sensor type to TYPE_ACCELEROMETER and the sensor change event as follow in source file "MainActivity.java". package com.example.mysensor; import android.app.activity; import android.os.bundle; import android.view.menu; import android.content.context; import android.widget.textview; import android.hardware.sensor; import android.hardware.sensorevent; import android.hardware.sensoreventlistener; import android.hardware.sensormanager; public class MainActivity extends Activity implements SensorEventListener { private SensorManager msensormanager; private Sensor msensor; float x, init_x; long lastupdatetime = 0; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // Get an instance of the sensor service, and use that to get an instance 4T026-1-A @ Peter Lo 2015 11

// of a particular sensor. msensormanager = (SensorManager) getsystemservice(context.sensor_service); msensor = msensormanager.getdefaultsensor(sensor.type_accelerometer); public void onsensorchanged(sensorevent event) { // Finds a view that was identified by the ID attribute from the XML TextView mtextview = (TextView) findviewbyid(r.id.textview1); // Capture the initial value if (init_x == 0) { init_x = event.values[0]; x = init_x - event.values[0]; // Time interval = Current Time - Last Update Time long timeinterval = System.currentTimeMillis() - lastupdatetime; // Obtain capture user shake > 300 ms if (timeinterval < 300) { lastupdatetime = System.currentTimeMillis(); else { if (x < -5) { mtextview.settext("left"); else if (x > 5) { mtextview.settext("right"); public void onaccuracychanged(sensor sensor, int accuracy) { public void onresume() { // Register a listener for the sensor super.onresume(); 4T026-1-A @ Peter Lo 2015 12

msensormanager.registerlistener(this, msensor, SensorManager.SENSOR_DELAY_NORMAL); public void onpause() { // Be sure to unregister the sensor when the activity pauses. super.onpause(); msensormanager.unregisterlistener(this); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; 2. Save and execute the app, you should able to obtain the direction (left or right) by shaking your mobile. 4T026-1-A @ Peter Lo 2015 13

4. Location Services 4.1 GPS Location 1. Create the Android application with the following attributes. Application Name: MyLocation Project Name: Package Name: MyLocation com.example.mylocation 2. Put four text views into the layout as follow: 3. The XML code for the layout look like: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity" > <TextView android:id="@+id/textview2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="latitude:" /> <TextView android:id="@+id/txtlatitude" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignbottom="@+id/textview2" android:layout_marginleft="19dp" android:layout_torightof="@+id/textview2" android:text="unknown" /> <TextView android:id="@+id/textview1" 4T026-1-A @ Peter Lo 2015 14

android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/textview2" android:layout_below="@+id/textview2" android:layout_margintop="18dp" android:text="longitude:" /> <TextView android:id="@+id/txtlongitude" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignbaseline="@+id/textview1" android:layout_alignbottom="@+id/textview1" android:layout_alignleft="@+id/txtlatitude" android:text="unknown" /> </RelativeLayout> 4. Modify the source file "MainActivity.java" as follow: package com.example.mylocation; import android.app.activity; import android.os.bundle; import android.view.menu; import android.content.context; import android.widget.textview; import android.location.criteria; import android.location.location; import android.location.locationlistener; import android.location.locationmanager; public class MainActivity extends Activity implements LocationListener { private double latitude, longitude; private TextView txtlatitude; private TextView txtlongitude; private LocationManager locationmanager; private String provider; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); 4T026-1-A @ Peter Lo 2015 15

setcontentview(r.layout.activity_main); txtlatitude = (TextView) findviewbyid(r.id.txtlatitude); txtlongitude = (TextView) findviewbyid(r.id.txtlongitude); // Get the location manager locationmanager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Define the criteria how to select the location provider Criteria criteria = new Criteria(); provider = locationmanager.getbestprovider(criteria, false); Location location = locationmanager.getlastknownlocation(provider); // Initialize the location fields if (location!= null) { // Provider selected onlocationchanged(location); else { txtlatitude.settext("unknown"); txtlongitude.settext("unknown"); public void onlocationchanged(location location) { latitude = (double) (location.getlatitude()); longitude = (double) (location.getlongitude()); txtlatitude.settext(string.valueof(latitude)); txtlongitude.settext(string.valueof(longitude)); public void onstatuschanged(string provider, int status, Bundle extras) { public void onproviderenabled(string provider) { 4T026-1-A @ Peter Lo 2015 16

public void onproviderdisabled(string provider) { public void onresume() { // Request updates at startup super.onresume(); locationmanager.requestlocationupdates(provider, 400, 1, this); public void onpause() { // Remove the location listener updates when Activity is paused super.onpause(); locationmanager.removeupdates(this); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; 5. Open the manifest file AndroidManifest.xml, and press [Add] in the Permission tab. Then select Uses Permission and press [OK]. 4T026-1-A @ Peter Lo 2015 17

6. Add the following user permission in "AndroidManifest.xml": android.permission.internet android.permission.access_fine_location android.permission.access_network_state android.permission.access_coarse_location 7. Save and execute the app, can you see the location information in emulator? Install this app into real mobile, and turn on GPS, can you see the location information correctly? 4.2 Mock Location in AVD 1. Select Windows Open Perspective DDMS. 4T026-1-A @ Peter Lo 2015 18

2. Select the DDMS tab. 3. Input 114.179531 and 22.305257 as the longitude and latitude, and then press Send. 4. Switch to the app again, the location should be display correctly. 4T026-1-A @ Peter Lo 2015 19

5. Answer 5.1 Maze Game 1. Create the Android application with the following attributes. Application Name: MyMazeGame Project Name: Package Name: MyMazeGame com.example.mymazegame 2. Right click the package src/com.example.mymazegame, and select New Class. Input Maze as the class name and press [Finish] button. 3. Modify the source code for Maze.java as follow: package com.example.mymazegame; import java.io.serializable; public class Maze implements Serializable { private static final long serialversionuid = 1L; public static final int UP = 0, DOWN = 1, RIGHT = 2, LEFT = 3; private boolean[][] verticallines; private boolean[][] horizontallines; private int sizex, sizey; private int currentx, currenty; private int finalx, finaly; // Stores the width and height of the maze // Stores the current location of the ball // Stores the finishing of the maze private boolean gamecomplete; 4T026-1-A @ Peter Lo 2015 20

public int getmazewidth() { return sizex; public int getmazeheight() { return sizey; public boolean move(int direction) { boolean moved = false; if (direction == UP) { if(currenty!= 0 &&!horizontallines[currenty-1][currentx]) { currenty--; moved = true; if (direction == DOWN) { if(currenty!= sizey-1 &&!horizontallines[currenty][currentx]) { currenty++; moved = true; if (direction == RIGHT) { if(currentx!= sizex-1 &&!verticallines[currenty][currentx]) { currentx++; moved = true; if (direction == LEFT) { if(currentx!= 0 &&!verticallines[currenty][currentx-1]) { currentx--; moved = true; if (moved) { if(currentx == finalx && currenty == finaly) { gamecomplete = true; 4T026-1-A @ Peter Lo 2015 21

return moved; public boolean isgamecomplete() { return gamecomplete; public void setstartposition(int x, int y) { currentx = x; currenty = y; public int getfinalx() { return finalx; public int getfinaly() { return finaly; public void setfinalposition(int x, int y) { finalx = x; finaly = y; public int getcurrentx() { return currentx; public int getcurrenty() { return currenty; public boolean[][] gethorizontallines() { return horizontallines; public void sethorizontallines(boolean[][] lines) { horizontallines = lines; 4T026-1-A @ Peter Lo 2015 22

sizex = horizontallines[0].length; public boolean[][] getverticallines() { return verticallines; public void setverticallines(boolean[][] lines) { verticallines = lines; sizey = verticallines.length; 4. Right click the package src/com.example.mymazegame, and select New Class. Input MazeCreator as the class name and press [Finish] button. 5. Modify the source code for MazeCreator.java as follow: package com.example.mymazegame; public class MazeCreator { public static Maze getmaze() { Maze maze = null; maze = new Maze(); boolean[][] vlines = new boolean[][]{ {true,false,false,false,true,false,false, {true,false,false,true,false,true,true, 4T026-1-A @ Peter Lo 2015 23

{false,true,false,false,true,false,false, {false,true,true,false,false,false,true, {true,false,false,false,true,true,false, {false,true,false,false,true,false,false, {false,true,true,true,true,true,false, {false,false,false,true,false,false,false ; boolean[][] hlines = new boolean[][]{ {false,false,true,true,false,false,true,false, {false,false,true,true,false,true,false,false, {true,true,false,true,true,false,true,true, {false,false,true,false,true,true,false,false, {false,true,true,true,true,false,true,true, {true,false,false,true,false,false,true,false, {false,true,false,false,false,true,false,true ; maze.setverticallines(vlines); maze.sethorizontallines(hlines); maze.setstartposition(0, 0); maze.setfinalposition(7, 7); return maze; 6. Right click the package src/com.example.mymazegame, and select New Class. Input GameView as the class name and press [Finish] button: 4T026-1-A @ Peter Lo 2015 24

7. Modify the source code for GameView.java as follow package com.example.mymazegame; import android.app.activity; import android.app.alertdialog; import android.content.context; import android.content.dialoginterface; import android.graphics.canvas; import android.graphics.color; import android.graphics.paint; import android.hardware.sensor; import android.hardware.sensorevent; import android.hardware.sensoreventlistener; import android.hardware.sensormanager; import android.view.view; public class GameView extends View implements SensorEventListener { // Width and height of the whole maze and width of lines which make the walls private int width, height, linewidth; // Size of the maze i.e. number of cells in it private int mazesizex, mazesizey; // Width and height of cells in the maze float cellwidth, cellheight; // Store result of cellwidth+linewidth and cellheight+linewidth respectively float totalcellwidth, totalcellheight; // The finishing point of the maze private int mazefinishx, mazefinishy; private Maze maze; private Activity context; private Paint line, red, background; boolean dragging = false; // Sensor for motion detection public SensorManager msensormanager; public Sensor msensor; 4T026-1-A @ Peter Lo 2015 25

public GameView(Context context, Maze maze) { super(context); this.context = (Activity)context; this.maze = maze; mazefinishx = maze.getfinalx(); mazefinishy = maze.getfinaly(); mazesizex = maze.getmazewidth(); mazesizey = maze.getmazeheight(); line = new Paint(); line.setcolor(color.black); red = new Paint(); red.setcolor(color.red); background = new Paint(); background.setcolor(color.yellow); setfocusable(true); this.setfocusableintouchmode(true); // Get an instance of the sensor service, and use that to get an instance of // a particular sensor. msensormanager = (SensorManager) context.getsystemservice(context.sensor_service); msensor = msensormanager.getdefaultsensor(sensor.type_rotation_vector); msensormanager.registerlistener(this, msensor, SensorManager.SENSOR_DELAY_NORMAL); protected void onsizechanged(int w, int h, int oldw, int oldh) { width = (w < h)?w:h; height = width; linewidth = 1; // For now square mazes // For now 1 pixel wide walls cellwidth = (width - ((float)mazesizex*linewidth)) / mazesizex; totalcellwidth = cellwidth+linewidth; cellheight = (height - ((float)mazesizey*linewidth)) / mazesizey; totalcellheight = cellheight+linewidth; red.settextsize(cellheight*0.75f); super.onsizechanged(w, h, oldw, oldh); 4T026-1-A @ Peter Lo 2015 26

protected void ondraw(canvas canvas) { // Fill in the background canvas.drawrect(0, 0, width, height, background); boolean[][] hlines = maze.gethorizontallines(); boolean[][] vlines = maze.getverticallines(); // Iterate over the boolean arrays to draw walls for(int i = 0; i < mazesizex; i++) { for(int j = 0; j < mazesizey; j++){ float x = j * totalcellwidth; float y = i * totalcellheight; if (j < mazesizex - 1 && vlines[i][j]) { // we'll draw a vertical line canvas.drawline(x + cellwidth, // Start X y, // Start Y x + cellwidth, y + cellheight, // Stop X // Stop Y line); if (i < mazesizey - 1 && hlines[i][j]) { // We'll draw a horizontal line canvas.drawline(x, y + cellheight, x + cellwidth, y + cellheight, // StartX // StartY // StopX // StopY line); int currentx = maze.getcurrentx(),currenty = maze.getcurrenty(); // Draw the ball canvas.drawcircle((currentx * totalcellwidth)+(cellwidth/2), (currenty * totalcellheight)+(cellwidth/2), (cellwidth*0.45f), // x // y // Radius red); 4T026-1-A @ Peter Lo 2015 27

// Draw the finishing point indicator canvas.drawtext("f", (mazefinishx * totalcellwidth) + (cellwidth*0.25f), (mazefinishy * totalcellheight) + (cellheight*0.75f), red); public void onaccuracychanged(sensor sensor, int accuracy) { public void onsensorchanged(sensorevent event) { if (true) { // Either X or Y changed boolean moved = false; // Obtain the rotate direction if (event.values[0] < 0 && event.values[1] > 0) { moved = maze.move(maze.up); else if (event.values[0] > 0 && event.values[1] < 0) { moved = maze.move(maze.down); else if (event.values[0] < 0 && event.values[1] < 0) { moved = maze.move(maze.left); else if (event.values[0] > 0 && event.values[1] > 0) { moved = maze.move(maze.right); if (moved) { // The ball was moved so we'll redraw the view invalidate(); if(maze.isgamecomplete()) { // Create alert Dialog with one Button AlertDialog.Builder alertdialog1 = new AlertDialog.Builder(context); // Set Dialog Title alertdialog1.settitle("level Complete"); // Set Dialog Message 4T026-1-A @ Peter Lo 2015 28

alertdialog1.setmessage("press [OK] to quit"); // Set OK Button alertdialog1.setpositivebutton("ok", new DialogInterface.OnClickListener() { public void onclick(dialoginterface dialog, int which) { // Handle button click context.finish(); ); // Showing Alert Message alertdialog1.show(); 8. Modify the source code for MainActivity.java as follow. package com.example.mymazegame; import android.os.bundle; import android.app.activity; import android.view.menu; public class MainActivity extends Activity { protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // setcontentview(r.layout.activity_main); Maze maze = MazeCreator.getMaze(); GameView view = new GameView(this, maze); setcontentview(view); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. 4T026-1-A @ Peter Lo 2015 29

getmenuinflater().inflate(r.menu.main, menu); return true; 9. Save and execute the app, then you can rotate your mobile to play the game. (This app does not workable in emulator. Moreover, these sensors are hardware-based and are available only if a device manufacturer has built them into a device). 4T026-1-A @ Peter Lo 2015 30