Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Tutorial for developing the Snake Game in Android: What is Android? Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language. Application Fundamentals: Android applications are written in the Java programming language. The Android SDK tools compile the code—along with any data and resource files—into an Android package, an archive file with an .apk suffix. All the code in a single .apk file is considered to be one application and is the file that Android-powered devices use to install the application. The objective of this android tutorial would be a) Install the Android SDK on Mac and configure with eclipse b) Create a sample application (Hello World) that runs on the Android Emulator and then create the snake game . We find the game is taking time to configure and run. c) Hence, the same game is uploaded in the Android Tablet and tested for its speed .It is running fast and it is ready to play. Three versions of the game are created. The first one wherein the snake eats the apple grows in size and increases its speed. This works with the Android tablet only when it is connected to the external keyboard. To avoid this, the second version of the game was created where in the snake is controlled by touching it by hand on the Android tablet. The third version was created for the fun element of the accelerometer which controls the movement of the snake. The purposes of all three versions are the same though. 1. Getting Started with Android Development This tutorial shows you how to download and install Android SDK to get you started developing Android applications. 1. Install Java : Check whether the system has Java already installed in it by going to Applications > Utilities > Terminal. Just type java –version . If it says a version, then Java download is not necessary. Current version is: 1.6.0_31 Otherwise, click http://www.oracle.com/technetwork/java/javase/downloads/jdk-7u4-downloads1591156.html and select the jdk-7u4- macosx-x64.dmg for Mac OS from Java SE development kit 7u4. Just download and install it.(For windows , select jdk-7u4-windowsx- i586.exe and download and install it). Otherwise upload the package named jdk-7u4- macosx-x64.dmg into the desktop from the zipped drive. 2. Install Eclipse: Go to http://www.eclipse.org/downloads/ to download a copy of eclipse. The page will look like this: The first item listed is "Eclipse IDE for Java Developers (98 MB)." On the right is a green, downward-pointing arrow. Next to that are links labeled "Mac OS X 32 Bit" and "Mac OS X 64 Bit." Click on the "Mac OS X 32 Bit" link. (For windows just choose the windows option and follow the same instructions of installation.) You will see a window like this: Click on the green, downward pointing arrow. A download of eclipse-java-helios-SR2macosx-cocoa.tar.gz will start. If you first get a window like this just click "OK" so that the downloaded file opens with Archive Utility. The download will go to your Downloads folder. You will normally have an icon for the Downloads folder on the right-hand side of the dock. Find eclipse-java-helios-SR2macosx-cocoa.tar.gz in your Downloads folder, and drag it to the Desktop. Then doubleclick it. You will see a folder named "eclipse." // Otherwise , just drag the eclipse-jeeindigo-SR2- macosx-cocoa.tar.gz from the zipped drive into the desktop and follow the instructions. 1. Drag the "eclipse" folder into your Applications folder. The easiest way to do so is to open a new window in the Finder and click on Applications in the list you get on the lefthand side. Then drag the "eclipse" folder in with the other applications. Make sure that you do not drag it into a folder that's already within Applications. In other words, when you're done, the Applications folder should have directly within it a folder named "eclipse." 2. (This step is not required, but it's strongly recommended.) Double click the "eclipse" folder. You'll see an application named "Eclipse"; it has a purple icon with white horizontal stripes. Drag it into your dock. Now you will be able to launch Eclipse by clicking on the icon in the dock. 3. You may now drag eclipse-java-helios-SR2- macosx-cocoa.tar.gz to the Trash. Empty the Trash whenever you wish. 4. When you launch Eclipse for the first time, you'll be asked "'Eclipse' is an application downloaded from the Internet. Are you sure you want to open it?" Click "Open." 5. You'll see something like the following window: Of course, the workspace name will have your user name in place of "thc." You can choose whatever place you want for your workspace, but it's easiest to just use the default you're given. I recommend that you just click the checkbox next to "Use this as the default and do not ask again" and then click "OK." 6. You'll then see the following screen: Click on the folded-over arrow on the right. You won't see this screen again, even if you quit Eclipse and relaunch it. 7. Now you'll see the following screen: 8. You have now installed Eclipse! 2.1. Install the ADT Plug-in Start Eclipse, then select Help > Software Updates or Help> Install New Software…. In the dialog that appears, click the Available Software/Install New Software tab. Click Add Site. · In the Add Site dialog that appears, Copy and paste this link into input box “Location/Work with”: https://dlssl.google.com/android/eclipse/ Back in the Available Software view, you should see the plugin.(For Windows ,just add the name as ADT plugin and check the developer tools box and continue with the instructions of mac). “Android Developer Tools”, and “Android Editors” should both be checked. The Android Editors feature is optional, but recommended. Then click on the button “Install …” Click on the button next Check the “I accept the terms of the license agreements” and click Finish. Eclipse will ask to restart, click on the button Yes. After restart, update your Eclipse preferences to point to the SDK directory: 2.2. Android SDK : Download the Android SDK from this link http://developer.android.com/s dk/index.html // Otherwise just drag the file from the zipped drive into the desktop and continue with the instructions below. Install the Android SDK (android-sdk_r17-macosx.zip). To install the Android SDK in Mac OS X, all you need to do is unzip the package that you downloaded, and place it in the Applications folder. Begin by right-clicking on the package you downloaded, and using the Archive Utility to extract the files. After you have extracted the files, you’ll see a newly created folder called android-sdk-macosx. Drag that in the Applications folder. 4. Install the ADT Plugin for Eclipse. This part of the procedure installs the Android Development Tools (ADT) plugin for Eclipse. It’s what ties together Eclipse and the Android SDK. You install it via Eclipse, using the Help…Install New Software menu of Eclipse. First thing is to fire up Eclipse. Double-click on the Eclipse executable in the Applications/Eclipse folder (or wherever you put it), and you’ll see the Eclipse splash screen. The first thing you’ll have to decide is where to configure your workspace. Unless you have a reason to change from the default, go with what it suggests. Once you have that set, and hit OK, the main Eclipse screen should come up. Now you want to go to Help…Install New Software, and configure the screen to hit the correct software repository. Here is the initial screen you’ll get. See the Add button on the right-hand side near the top? Click it, and here’s what you’ll get. OK, that’s not totally what you’ll get. You’ll need to type in both the Name ( ADT Plugin for Eclipse) and the Location (https://dl-ssl.google.com/android/eclipse/). Now you can hit OK. After a few seconds it’ll connect to the Google site, and then you’ll see this screen . Go ahead and hit Select All as I’ve done in this example . Hit Next to review the Install Details. Hit Next again, and select “I accept the terms of the license agreements.” That should enable the Finish button, which you should now hit. The following screen will pop up, which indicates you are now installing the software! In the course of the install, you may see the following security warning. Just go ahead and hit OK and things will proceed. At this point, you may get a series of errors, and one of them may look like this. Click on Open Preferences, and see this screen . Click on Browse and navigate to where you put the Android SDK folder. It’ll look like this Click Apply, then OK, and you’re all done! Now it’s time to configure the Android SDK for Development Tools and the Google APIs. You’re almost done! 1. Configure the Android SDK for Development Tools and Google API. This is where you configure the Android SDK Manager to download the tools you will need to create the application. This is essentially downloading the Google API's Platform 2.2 and API level 8. Start by bringing up the Android SDK Manager in Eclipse. Do this by starting Eclipse, then going to Window…Android SDK Manager. The following screen will appear, and your goal is to make it look like the image you see here. Select the Android 3.0 version and its corresponding tools and packages which is compatible with our application.(The game of Snake) Now click Install 6 packages (or whatever number you end up having), and you’ll get this screen. Click on the Accept All radio button, which should turn all the checkmarks in the packages list to green. Now hit Install. Watch the log until it says you are done and you can close. Then hit Close. This part of the process may take some time depending on the speed of your Internet connection. Once the install is done, and it says you can hit Close, you’ve successfully installed the Android SDK, Eclipse, and the ADT Plugin for Eclipse! Configuring a Virtual Device (Creating an AVD) : Once you have installed the required packages, you can use the Android SDK and AVD Manager to set up a virtual device that can be used in your development environment. This allows you to test your applications without requiring a physical Android device. You can set up a virtual device as follows: 1. Make sure the Android SDK and AVD Manager is running. To start AVD Manager Click on Window > AVD Manager. 2. Choose Virtual devices from the left hand panel (if you see that or go to step 3). 3. Select a file name New... . 4. Type in a name for the file (Android-Test) for the virtual device. 5. Set the Target to at least Android 2.2 - API Level 8.(In our application , set the target as android 3.0) 6. Fill in the SD Card Size. 7. Optionally enable Snapshot. This speeds up the launch of the emulator. 8. Select Create AVD. Starting the Virtual Device Simulator You can launch the emulator by highlighting the virtual device you created and selecting Start... . 2., Create a New Android Project After you've created an AVD you can move to the next step and start a new Android project in Eclipse. 1. In Eclipse, select File > New > Project.... If the ADT Plugin for Eclipse has been successfully installed, the resulting dialog should have a folder labeled "Android" which should contain "Android Project. Select "Android Project" and click Next. 2. Fill in the project details with the following values: o Project name: HelloAndroid o Build Target: Select a platform version that is equal to or lower than the target you chose for your AVD. o Application name: Hello, Android o Package name: com.example.helloandroid (or your own private namespace) o Create Activity: HelloAndroid Click Finish. Here is a description of each field: Project Name This is the Eclipse project name — the name of the directory that contains the project files. Build Target This is the version of the Android SDK that you're using to build your application. For example, if you choose Android 2.1, your application will be compiled against the Android 2.1 platform library. The target you choose here does not have to match the target you chose for your AVD; however, the target must be equal to or lower than the target you chose for your AVD. Android applications are forward-compatible, which means an application will run on the platform against which it is built as well as all platforms that are released in the future. For example, an application that is built against the 2.1 platform library will run normally on an AVD or device that is running the 2.3.3. The reverse is not true. Application Name This is the human-readable title for your application — the name that appears on the Android device. Package Name This is the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under. This also sets the package name under which the stub Activity is generated. Your package name must be unique across all packages installed on the Android system; for this reason, it's important to use a standard domain-style package for your applications. The example above uses the "com.example" namespace, which is a namespace reserved for example documentation — when you develop your own applications, you should use a namespace that's appropriate to your organization or entity. Create Activity This is the name for the class stub that is generated by the plugin. This is a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application. Min SDK Version This value specifies the minimum API Level on which your application will run. The Min SDK Version should be the same as the Build Target you chose. For example, if the Build Target is Android 2.1, then the Min SDK Version should be 7 or lower (it can never be higher than 7). For more information, see Android API Levels. Other fields: The checkbox for "Use default location" allows you to change the location on disk where the project's files are generated and stored. Your Android project is now ready. It should be visible in the Package Explorer on the left. Open the HelloAndroid.java file, located inside HelloAndroid > src > com.example.helloandroid. It should look like this: package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } Notice that the class is based on the Activity class. An Activity is a single application entity that is used to perform actions. An application may have many separate activities, but the user interacts with them one at a time. The onCreate() method is called by the Android system when your Activity starts — it is where you should perform all initialization and UI setup. An activity is not required to have a user interface, but usually does. Now let's modify some code! Construct the UI Take a look at the revised code below and then make the same changes to your HelloAndroid class. The bold items are lines that have been added. package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; import android.widget.TextVie w; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextVie w tv = ne w TextVie w(this); tv.setText("Hello, Android"); setContentView(tv); } } Tip: An easy way to add import packages to your project is to press Ctrl-Shift-O (Cmd-ShiftO, on Mac). This is an Eclipse shortcut that identifies missing packages based on your code and adds them for you. You may have to expand the import statements in your code for this to work. An Android user interface is composed of hierarchies of objects ca lled Views. A View is a drawable object used as an element in your UI layout, such as a button, image, or (in this case) a text label. Each of these objects is a subclass of the View class and the subclass that handles text is TextView. In this change, you create a TextView with the class constructor, which accepts an Android Context instance as its parameter. A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. The Activity class inherits from Context, and because your HelloAndroid class is a subclass of Activity, it is also a Context. So, you can pass this as your Context reference to the TextView. Next, you define the text content with setText(). Finally, you pass the TextView to setContentView() in order to display it as the content for the Activity UI. If your Activity doesn't call this method, then no UI is present and the system will display a blank screen. There it is — "Hello, World" in Android! The next step, of course, is to see it running. Run the Application The Eclipse plugin makes it easy to run your applications: 1. Select Run > Run. 2. Select "Android Application". The Eclipse plugin automatically creates a new run configuration for your project and then launches the Android Emulator. Depending on your environment, the Android emulator might take several minutes to boot fully, so please be patient. When the emulator is booted, the Eclipse plugin installs your application and launches the default Activity. You should now see something like this: The "Hello, Android" you see in the grey bar is actually the application title. The Eclipse plugin creates this automatically (the string is defined in the res/values/strings.xml file and referenced by your AndroidManifest.xml file). The text below the title is the actual text that you have created in the TextView object. Upgrade the UI to an XML Layout The "Hello, World" example you just completed uses what is called a "programmatic" UI layout. This means that you constructed and built your application's UI directly in source code. If you've done much UI programming, you're probably familiar with how brittle that approach can sometimes be: small changes in layout can result in big source-code headaches. It's also easy to forget to properly connect Views together, which can result in errors in your layout and wasted time debugging your code. That's why Android provides an alternate UI construction model: XML-based layout files. The easiest way to explain this concept is to show an example. Here's an XML layout file that is identical in behavior to the programmatically-constructed example: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello"/> The general structure of an Android XML layout file is simple: it's a tree of XML elements, wherein each node is the name of a View class (this example, however, is just one View element). You can use the name of any class that extends View as an element in your XML layouts, including custom View classes you define in your own code. This structure makes it easy to quickly build up UIs, using a more simple structure and syntax than you would use in a programmatic layout. This model is inspired by the web development model, wherein you can separate the presentation of your application (its UI) from the application logic used to fetch and fill in data. In the above XML example, there's just one View element: the TextView, which has five XML attributes. Here's a summary of what they mean: Attribute Meaning xmlns:android This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute. android:id This attribute assigns a unique identifier to the TextView element. You can use the assigned ID to reference this View from your source code or from other XML resource declarations. This attribute defines how much of the available width on the screen this android:layout_width View should consume. In this case, it's the only View so you want it to take up the entire screen, which is what a value of "fill_parent" means. android:layout_height This is just like android:layout_width, except that it refers to available screen height. android:text This sets the text that the TextView should display. In this example, you use a string resource instead of a hard-coded string value. The hello string is defined in the res/values/strings.xml file. This is the recommended practice for inserting strings to your application, because it makes the localization of your application to other languages graceful, without need to hard-code changes to the layout file. For more information, see Resources and Internationalization. These XML layout files belong in the res/layout/ directory of your project. The "res" is short for "resources" and the directory contains all the non-code assets that your application requires. In addition to layout files, resources also include assets such as images, sounds, and localized strings. Landscape layout When you want a different design for landscape, put your layout XML file inside /res/layoutland. Android will automatically look here when the layout changes. Without this special landscape layout defined, Android will stretch the default layout. The Eclipse plugin automatically creates one of these layout files for you: main.xml. In the "Hello World" application you just completed, this file was ignored and you created a layout programmatically. This was meant to teach you more about the Android framework, but you should almost always define your layout in an XML file instead of in your code. The following procedures will instruct you how to change your existing application to use an XML layout. 1. In the Eclipse Package Explorer, expand the /res/layout/ folder and open main.xml (once opened, you might need to click the "main.xml" tab at the bottom of the window to see the XML source). Replace the contents with the following XML: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello"/> Save the file. 2. Inside the res/values/ folder, open strings.xml. This is where you should save all default text strings for your user interface. If you're using Eclipse, then ADT will have started you with two strings, hello and app_name. Revise hello to something else. Perhaps "Hello, Android! I am a string resource!" The entire file should now look like this: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello, Android! I am a string resource!</string> <string name="app_name">Hello, Android</string> </resources> 3. Now open and modify your HelloAndroid class and use the XML layout. Edit the file to look like this: package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } When you make this change, type it by hand to try the code-completion feature. As you begin typing "R.layout.main" the plugin will offer you suggestions. You'll find that it helps in a lot of situations. Instead of passing setContentView() a View object, you give it a reference to the layout resource. The resource is identified as R.layout.main, which is actually a compiled object representation of the layout defined in /res/layout/main.xml. The Eclipse plugin automatically creates this reference for you inside the project's R.java class. If you're not using Eclipse, then the R.java class will be generated for you when you run Ant to build the application. (More about the R class in a moment.) Now re-run your application — because you've created a launch configuration, all you need to do is click the green arrow icon to run, or select Run > Run History > Android Activity. Other than the change to the TextView string, the application looks the same. After all, the point was to show that the two different layout approaches produce identical results. Note: You may have to unlock the screen on the emulator to see your application — just as you would unlock the screen on a device. R class: In Eclipse, open the file named R.java (in the gen/ [Generated Java Files] folder). It should look something like this: package com.example.helloandroid; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class id { public static final int textview=0x7f050000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } } A project's R.java file is an index into all the resources defined in the file. You use this class in your source code as a sort of short-hand way to refer to resources you've included in your project. This is particularly powerful with the code-completion features of IDEs like Eclipse because it lets you quickly and interactively locate the specific reference you're looking for. It's possible yours looks slightly different than this (perhaps the hexadecimal values are different). For now, notice the inner class named "layout", and its member field "main". The Eclipse plugin noticed the XML layout file named main.xml and generated a class for it here. As you add other resources to your project (such as strings in the res/values/string.xml file or drawables inside the res/drawable/ directory) you'll see R.java change to keep up. When not using Eclipse, this class file will be generated for you at build time (with the Ant tool). You should never edit this file by hand. Debug Your Project: The Android Plugin for Eclipse also has excellent integration with the Eclipse debugger. To demonstrate this, introduce a bug into your code. Change your HelloAndroid source code to look like this: package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Object o = null; o.toString(); setContentView(R.layout.main); } } This change simply introduces a NullPointerException into your code. If you run your application again, you'll eventually see this: Press "Force Quit" to terminate the application and close the emulator window. To find out more about the error, set a breakpoint in your source code on the line Object o = null; (double-click on the marker bar next to the source code line). Then select Run > Debug History > Hello, Android from the menu to enter debug mode. Your app will restart in the emulator, but this time it will suspend when it reaches the breakpoint you set. You can then step through the code in Eclipse's Debug Perspective, just as you would for any other application. Creating a simple Snake game: Snake is a classic game in which the player controls a snake that moves around and eats fruit. With each fruit that the snake eats, it grows in length by one, and the player earns one point. The player loses the game when the snake either collides with it's tail, or a wall. This series will cover the creation of the snake game from start to finish, and will provide full source code at the end. This will be broken up into several parts, each covering a different section of the game before putting it all together and supplying the source code at the end. Android is structured so that applications may use relevant pieces of other applications, without having to load all of the other application. This ability is important in implementing "lean and mean" applications that use minimal resources, and implies that well-written Android applications must be highly modular, with multiple entry points. The snake game also consists of common files as in android with additions made to it for the purpose of this gaming app lication. Let us see the version 2 in detail since we can run it with the help of both simulator and Android tablet. Version 2: Click on New>Android Project; Type in the project name as snake. click ok. Type in the application name as snake,1 and package name as com.snake3.android .Just select the activity and click finish.(as we did for Hello Android). Loading the resources: Download the resources required from the internet and zip it into a folder. Import them into the res > drawable > .png file. 1. 2. 3. 4. Button.png Icon.png Logo.png Tiles.png The Resources folder is given below to easily import into Eclipse. The AndroidManifest.xml File First start creating the android manifest file by getting into Res > Android manifest.xml Android must know that a component of an application exists before it can start it. This is accomplished by having applications declare their components in an XML manifest file that is always called AndroidManifest.xml, and that every application must contain. As we shall find, the manifest file does many other things, such as naming any external libraries the application needs to be linked against and identifying any permissions the application expects to be granted, but its most fundamental task is to inform Android about the application's components. Modify the AndroidManifest.xml file for the snake game to add any specific permissions that you know the project will require. This file declares the content of the Snake application. The code below will add the required lines: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.snake3.android" android:versionName="2.7" android:versionCode="9"> <uses-sdk android:minSdkVersion="7" /> <application android:icon="@drawable/icon" android:label="@string/app_name" android:allowClearUserData="false" android:description="@string/description" android:enabled="true" android:testOnly="false" android:killAfterRestore="true" android:restoreNeedsApplication="true" android:allowTaskReparenting="true" android:hasCode="true" android:persistent="false" android:debuggable="false"> <activity android:name=".Snake3" android:label="@string/app_name" android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> in which the activity, .snake3 is declared. The application starts control from the manifest file which primarily refers the main files. This is to make the device and the game application to communicate with each other. Creating the layout: The recommended way to lay out the view hierarchy is with an XML la yout file. Here, we use the relative layout: Relative Layout is a View Group that displays child View elements in relative positions. The position of a View can be specified as relative to sibling elements (such as to the left-of or below a given element) or in positions relative to the Relative Layout area (such as aligned to the bottom, left of center). A Relative Layout is a very powerful utility for designing a user interface because it can eliminate nested View Groups. To create this, get into res > layout > main.xml. Here is the simple XML relative layout file which we call in the main. xml file in this snake game: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.snake3.android.playField android:id="@+id/playField1" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_width="fill_parent" android:layout_height="fill_parent"> </com.snake3.android.playField> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/button1" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:background="@drawable/button" android:textAppearance="@style/bold" android:freezesText="true" android:textColor="@color/RED" android:text="@string/startButton"></Button> <TextView android:id="@+id/textView1" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="TextView" android:layout_above="@+id/button1" android:layout_centerHorizontal="true"></TextView> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:id="@+id/button2" android:layout_alignParentTop="true" android:layout_alignParentRight="true"></Button> <ImageView android:layout_width="wrap_content" android:src="@drawable/logo" android:layout_height="wrap_content" android:id="@+id/imageView1" android:layout_alignParentTop="true" android:layout_centerHorizontal="true"></ImageView> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/button3" android:layout_below="@+id/button1" android:layout_alignLeft="@+id/button1" android:background="@drawable/button" android:layout_centerInParent="true" android:textAppearance="@style/bold" android:focusableInTouchMode="true" android:textColor="@color/RED" android:text="@string/credits"></Button> </RelativeLayout> This layout would create a TextView , an image view and 3 buttons, arrayed in a relative layout in the Android window. As long as you follow the rules, you do not have to worry about managing the relationship between XML layout of the UI and the Java code that will reference it. Basically you must just place correctly written code in a standardized set of directories and Android will do the rest. When you load a layout resource, Android automatically initializes these run-time objects, corresponding to the elements in your layout. Click res > values > string.xml file and type in the following code : <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">SnakeGame</string> …. <string name="startButton">Start</string> <string name="pauseButton">Pause</string> <string name="restartButton">Restart</string> <style name="bold"><item name="android:textSize">20sp</item></style> <string name="score">Your Score was: </string> <string name="description">Snake, swipe in the direction you want to move</string> <color name="RED">#F00</color> <string name="credits">Credits</string> </resources> The resources file will automatically change as the screen shown below: The Graphical layout of the main.xml will look like this: The Buildconfig.Java and R.Java files in the folder gen are automatically created when changes to the xml files we created are made. The package com.snake3.android is the heart of the game which consists of four java files: 1. 2. 3. 4. Snake.java Game Engine.java gameThread.java playfield.java Snake.java is the file that contains labels and buttons and how they are made to work: package com.snake3.android; /**import these buttons and alertdialog which are existing already*/ import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; /** When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits. onCreate() is a method that is created when the activity is initialized. */ public class Snake3 extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /** Buttons,Textview and the Imageview locates the R.java(Resources.java file) with the help of the id`s.*/ final playField game = (playField)findViewById(R.id.playField1); final Button start = (Button)findViewById(R.id.button1); final Button pause = (Button)findViewById(R.id.button2); final TextView score = (TextView)findViewById(R.id.textView1); final ImageView logo = (ImageView)findViewById(R.id.imageView1); final Button credit = (Button)findViewById(R.id.button3); final Builder credits = new AlertDialog.Builder(this); credits.setTitle("Credits"); credits.setMessage("Credits"); credits.setPositiveButton("ok", null); /** setting the teat color and visibility */ score.setTextColor(Color.RED); score.setVisibility(View.GONE); score.setTextAppearance(getApplicationContext(), R.style.bold); pause.setVisibility(View.GONE); pause.setBackgroundResource(R.drawable.button); pause.setTextColor(Color.RED); pause.setTextAppearance(getApplicationContext(), R.style.bold); pause.setText(R.string.pauseButton); credit.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { credits.show(); } }); /** setting the onClickListeners to start ,pause the game ,score and logo visibility when the game is started */ start.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { game.startGame(); pause.setVisibility(View.VISIBLE); start.setVisibility(View.GONE); score.setVisibility(View.GONE); logo.setVisibility(View.GONE); credit.setVisibility(View.GONE); } }); pause.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { game.pause(); } }); Timer timer; TimerTask task; final Handler timerHandle; timerHandle = new Handler(); timer=new Timer(); task = new TimerTask() { @Override public void run() { timerHandle.post(new Runnable() { public void run() { if(game!=null&&game.gameOn()&&game.lost()){ String endText = getString(R.string.score)+game.getScore(); start.setVisibility(View.VISIBLE); score.setVisibility(View.VISIBLE); credit.setVisibility(View.VISIBLE); start.setText(R.string.restartButton); score.setText(endText); } } }); } }; timer.schedule(task, 1000, 500); } } Game Engine.java: At the heart of every game is the engine. The engine is responsible for updating the game at fixed intervals, in response to events, or a combination of the two. In the case of the Snake Game, we need to update the game at regular intervals, and accept user input from the Keyboard. package com.snake3.android; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import android.graphics.Bitmap; import android.os.Handler; /** To start, we're going to create a new class and name it gameEngine. This class will be responsible for handling most of the game's logic, the game loop, and window creation .*/ public class gameEngine { /** The private variables are declared. Walls, snake and direction are declared in array.*/ private ArrayList<Float> walls; private ArrayList<Float> snake; private ArrayList<Integer> direction; private int width; private int height; private int tileWidth; private int tileHeight; private int length; private int currentd; private float[] apple; private Timer snakeMover; private TimerTask task; private Handler timerHandle; private int score; boolean playing; boolean lost; boolean paused; /** The arguments width , height and Bitmap tile are passed into the gameEngine . The snake grows in size when the game is in the running state.*/ public gameEngine(int _width, int _height, Bitmap tile) { paused=false; walls = new ArrayList<Float>(); snake = new ArrayList<Float>(); direction = new ArrayList<Integer>(); width=_width; height=_height; tileWidth = tile.getWidth(); tileHeight= tile.getHeight(); setWalls(); direction.add(Integer.valueOf(3)); length=5; timerHandle = new Handler(); score=0; apple = new float[2]; generateApple(); playing = false; lost=false; } /** If the snake eats the apple ,then the score increases.*/ public void checkCollide() { if(snake.get(0)==apple[0]&&snake.get(1)==apple[1]) { score++; generateApple(); growSnake(); updateTimer(((10000/(height/tileHeight)))/((score/3.0)+1)); } /** When the snake hits the walls ,the game will cancel and the player loses the game*/ for(int i=0;i<walls.size()-1;i+=2) { if(snake.get(0).equals(walls.get(i))&&snake.get(1).equals(walls. get(i+1))) { lost=true; playing=false; snakeMover.cancel(); } } for(int i=2;i<snake.size()-1;i+=2) { if(snake.get(0).equals(snake.get(i))&&snake.get(1).equals(snake. get(i+1))) { lost=true; playing=false; snakeMover.cancel(); } } } public boolean getPlaying() { return playing; } public void setPlaying(boolean play) { playing = play; } public void updateTimer(double d) { if(snakeMover!=null) { snakeMover.cancel(); } snakeMover=new Timer(); task = new TimerTask() { @Override public void run() { timerHandle.post(new Runnable() { public void run() { if(playing) { moveSnake(); } } }); } }; snakeMover.schedule(task, 0, (long) d); } public void generateApple() { int max = width/tileWidth; max-=3; int t=(int) ((Math.random()*10000)%max); t+=2; apple[0]=t*tileWidth; max = height/tileHeight; max-=7; t=(int) ((Math.random()*10000)%max); t+=6; apple[1]=t*tileHeight; } public float[] getApple() { return apple; } public void initSnake() { length=5; direction = new ArrayList<Integer>(); direction.add(Integer.valueOf(3)); lost=false; snake = new ArrayList<Float>(); score=0; for(int i=0;i<length;i++) { snake.add(Float.valueOf(tileWidth*(20))+(tileWidth*i)); snake.add(Float.valueOf(tileHeight*(20))); } updateTimer(10000/(height/tileHeight)); } public void setWalls() { for(int x=0;x<width;x+=tileWidth) { for(int y=tileHeight*5;y<height;y+=tileHeight) { if(x==0||x==width-tileWidth||y==tileHeight*5||y>=heighttileHeight) { walls.add(Float.valueOf(x)); walls.add(Float.valueOf(y)); } } } } public ArrayList<Float> getWalls() { return walls; } public ArrayList<Float> getSnake() { return snake; } public void growSnake() { snake.add(snake.get(snake.size()-2)); snake.add(snake.get(snake.size()-2)); } public void setDirection(int d) { direction.add(Integer.valueOf(d)); sanitizeDirection(); } public void sanitizeDirection() { if(direction.size()>0) { if(direction.get(0)==currentd||direction.get(0)==(currentd+2)%4) { direction.remove(0); } for(int i=1;i<direction.size();i++) { if(i<direction.size()) { if(direction.get(i)==direction.get(i1)||direction.get(i)==(direction.get(i-1)+2)%4) { direction.remove(i); } } } } } public void moveSnake() { for(int i=snake.size()-1;i>=0;i-=2) { if(i>2) { snake.set(i, snake.get(i-2)); snake.set(i-1, snake.get(i-3)); } else { if(direction.size()>0) { currentd=direction.remove(0); } switch(currentd) { case 0: snake.set(1, Float.valueOf(snake.get(1)+tileHeight)); break; case 1: snake.set(0, Float.valueOf(snake.get(0)+tileWidth)); break; case 2: snake.set(1, Float.valueOf(snake.get(1)-tileHeight)); break; case 3: snake.set(0, Float.valueOf(snake.get(0)-tileWidth)); break; } } } checkCollide(); } public int getScore() { return score; } public boolean lost() { return lost; } public void pause() { if(!paused) { snakeMover.cancel(); paused=true; } else { paused=false; updateTimer((10000/(height/tileHeight))/((score/3)+1)); } } } Game thread.java package com.snake3.android; import android.graphics.Canvas; import android.view.SurfaceHolder; public class gameThread extends Thread { private SurfaceHolder _surfaceHolder; private playField _playField; private boolean _run = false; public gameThread(SurfaceHolder surfaceHolder, playField playField){ _surfaceHolder = surfaceHolder; _playField = playField; } public void setRunning(boolean run) { _run = run; } @Override public void run() { Canvas c; while(_run) { c = null; try { c = _surfaceHolder.lockCanvas(null); synchronized (_surfaceHolder) { _playField.onDraw(c); } } finally { if(c != null) { _surfaceHolder.unlockCanvasAndPost(c); } } } } } Playfield.java: The next step in creating the Snake Game is to create the world(playfield). Without the world, there would be no where for the game to take place, which wouldn't be fun at all. In the case of the Snake Game, the world will be an array of tiles, each with a type, which we can make use of when writing the game's logic. Our game world will be stored in a new class named GameBoard package com.snake3.android; import import import import import import import import import import import android.content.Context; android.graphics.Bitmap; android.graphics.BitmapFactory; android.graphics.Canvas; android.graphics.Color; android.graphics.LightingColorFilter; android.graphics.Paint; android.util.AttributeSet; android.view.MotionEvent; android.view.SurfaceHolder; android.view.SurfaceView; public class playField extends SurfaceView implemen ts SurfaceHolder.Callback { private gameThread _thread; private Bitmap tile; private Paint wall; private Paint snake; private Paint apple; private gameEngine engine; private double initX; private double finalX; private double initY; private double finalY; public playField(Context context, AttributeSet attrs) { super(context, attrs); getHolder().addCallback(this); setFocusable(true); _thread = new gameThread(getHolder(),this); tile = BitmapFactory.decodeResource(getResources(), R.drawable.tiles); setupPaints(); } public void setupPaints() { wall = new Paint(); snake = new Paint(); apple = new Paint(); apple.setColorFilter(new LightingColorFilter(Color.RED, 1)); wall.setColorFilter(new LightingColorFilter(Color.BLUE, 1)); snake.setColorFilter(new LightingColorFilter(Color.GREEN, 1));//*/ } public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { } public void surfaceCreated(SurfaceHolder arg0) { if (_thread.getState() == Thread.State.TERMINATED) { _thread = new gameThread(getHolder(),this); _thread.setRunning(true); _thread.start(); } else { _thread.setRunning(true); _thread.start(); } engine = new gameEngine(getWidth(),getHeight(),tile); engine.initSnake(); } public void surfaceDestroyed(SurfaceHolder arg0) { boolean retry = true; _thread.setRunning(false); while (retry) { try { _thread.join(); retry = false; } catch (InterruptedException e) { } } } public void onDraw(Canvas canvas) { canvas.drawColor(Color.BLACK); if(engine!=null) { for(int i=0;i<engine.getWalls().size()-1;i+=2) { canvas.drawBitmap(tile, engine.getWalls().get(i), engine.getWalls().get(i+1), wall); } for(int i=0;i<engine.getSnake().size()-1;i+=2) { canvas.drawBitmap(tile, engine.getSnake().get(i), engine.getSnake().get(i+1), snake); } canvas.drawBitmap(tile, engine.getApple()[0],engine.getApple()[1] , apple); } } public boolean onTouchEvent(MotionEvent event) { if(engine.getPlaying()) { if(event.getAction()==MotionEvent.ACTION_DOWN) { initX=event.getX(); initY=event.getY(); } double totY=Math.abs(Math.abs(finalY)-Math.abs(initY)); double totX=Math.abs(Math.abs(finalX)-Math.abs(initX)); if(event.getAction()==MotionEvent.ACTION_MOVE) { finalX=event.getX(); finalY=event.getY(); totY=Math.abs(Math.abs(finalY)-Math.abs(initY)); totX=Math.abs(Math.abs(finalX)-Math.abs(initX)); float threshold=20; if(totY>threshold||totX>threshold) { if(totX>totY) { if(finalX>initX) { engine.setDirection(1); } else if (finalX<initX) { engine.setDirection(3); } } else if(totY>totX) { if(finalY>initY) { engine.setDirection(0); } else if (finalY<initY) { engine.setDirection(2); } } initX=finalX; initY=finalY; } } } return true; } public void startGame() { engine.setPlaying(true); engine.initSnake(); } public boolean gameOn() { return (engine!=null); } public int getScore() { return engine.getScore(); } public boolean lost() { return engine.lost(); } public void pause() { engine.pause(); } } Once we are done with all the four files the game is all set to run it. Click Project > Clean and clean the project for all the changes we`ve made. Now right click or control click Snake3 and refresh. Now, control click and build project . Finally ,run the project as Run > Run As > Android Application. Now, it connects to the AVD . Unlock the lock which is displayed and double click on APPs icon. A set of apps displays from which the Snake 2 is selected. The game opens up and we are all set to play the game. The screen looks like this: Play it and become the highest scorer.