Repository: googlesamples/android-play-games-in-motion Branch: master Commit: f422166d2f14 Files: 109 Total size: 479.0 KB Directory structure: gitextract_6xtmc2to/ ├── .gitignore ├── .gitmodules ├── .idea/ │ ├── .name │ ├── compiler.xml │ ├── copyright/ │ │ ├── Apache_2_0.xml │ │ └── profiles_settings.xml │ ├── encodings.xml │ ├── gradle.xml │ ├── libraries/ │ │ ├── appcompat_v7_21_0_3.xml │ │ ├── junit_3_8.xml │ │ ├── play_services_6_1_71.xml │ │ ├── support_annotations_21_0_3.xml │ │ └── support_v4_21_0_3.xml │ ├── misc.xml │ ├── modules.xml │ ├── scopes/ │ │ └── scope_settings.xml │ └── vcs.xml ├── CONTRIBUTING ├── ExampleGame.iml ├── LICENSE ├── app/ │ ├── app.iml │ ├── build.gradle │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── google/ │ │ └── fpl/ │ │ └── gim/ │ │ └── examplegame/ │ │ └── MissionParseTest.java │ └── main/ │ ├── AndroidManifest.xml │ ├── assets/ │ │ ├── legacy_missions/ │ │ │ ├── choice_mission.xml │ │ │ ├── mission.xml │ │ │ ├── sfx mission.xml │ │ │ ├── spoken_plus_timer_mission.xml │ │ │ ├── texttospeechmission.xml │ │ │ └── timermission.xml │ │ └── missions/ │ │ ├── 01_sample_mission_1.xml │ │ ├── 02_sample_mission_2.xml │ │ ├── ex_01_timer_moment.xml │ │ ├── ex_02_spoken_text_moment.xml │ │ ├── ex_03_choice_moment.xml │ │ ├── ex_04_sfx_moment.xml │ │ ├── ex_05_broken_timer_moment.xml │ │ └── ex_06_long_timer_mission.xml │ ├── java/ │ │ └── com/ │ │ └── google/ │ │ └── fpl/ │ │ └── gim/ │ │ └── examplegame/ │ │ ├── Choice.java │ │ ├── ChoiceMoment.java │ │ ├── ChoiceMomentData.java │ │ ├── MainActivity.java │ │ ├── MainService.java │ │ ├── Mission.java │ │ ├── MissionData.java │ │ ├── Moment.java │ │ ├── MomentData.java │ │ ├── Outcome.java │ │ ├── SfxMoment.java │ │ ├── SfxMomentData.java │ │ ├── SpokenTextMoment.java │ │ ├── SpokenTextMomentData.java │ │ ├── TimerMoment.java │ │ ├── TimerMomentData.java │ │ ├── google/ │ │ │ ├── FitDataTypeSetting.java │ │ │ ├── FitResultCallback.java │ │ │ └── GoogleApiClientWrapper.java │ │ ├── gui/ │ │ │ ├── EndSummaryFragment.java │ │ │ ├── FitnessDataDisplayFragment.java │ │ │ ├── GameViews.java │ │ │ ├── MissionSelectionFragment.java │ │ │ ├── MusicSelectionFragment.java │ │ │ ├── NotificationOptions.java │ │ │ ├── RunSpecificationSelectionFragment.java │ │ │ └── StartMenuFragment.java │ │ └── utils/ │ │ ├── MissionParseException.java │ │ ├── MissionParser.java │ │ └── Utils.java │ └── res/ │ ├── anim/ │ │ ├── slide_in_right.xml │ │ └── slide_out_left.xml │ ├── drawable/ │ │ └── weapon_charge_progress.xml │ ├── layout/ │ │ ├── activity_main.xml │ │ ├── end_screen.xml │ │ ├── menu_list_item.xml │ │ ├── menu_mission_list.xml │ │ ├── menu_music_selection.xml │ │ ├── menu_run_specifications.xml │ │ ├── menu_start.xml │ │ ├── placeholder_fragment.xml │ │ └── step_display.xml │ ├── menu/ │ │ └── main.xml │ ├── values/ │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── ids.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── values-w820dp/ │ └── dimens.xml ├── build.gradle ├── docs/ │ ├── generate_docs.py │ └── src/ │ ├── contributing.md │ ├── doxyfile │ ├── doxygen_layout.xml │ ├── index.md │ └── programmers_guide/ │ ├── assets.md │ ├── audio.md │ ├── building.md │ ├── core.md │ ├── gameplay.md │ ├── google_api.md │ ├── mission.md │ └── overview.md ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── prototype.iml ├── readme.md └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ #built application files *.apk *.ap_ # files for the dex VM *.dex # Java class files *.class # generated files bin/ gen/ build/ app/build/ # Local configuration file (sdk path, etc) local.properties # Windows thumbnail db Thumbs.db # OSX files .DS_Store # Eclipse project files .classpath .project # Android Studio project files .idea/workspace.xml .gradle ================================================ FILE: .gitmodules ================================================ [submodule "dependencies/fplutil"] path = dependencies/fplutil url = http://github.com/google/fplutil.git ================================================ FILE: .idea/.name ================================================ ExampleGame ================================================ FILE: .idea/compiler.xml ================================================ ================================================ FILE: .idea/copyright/Apache_2_0.xml ================================================ ================================================ FILE: .idea/copyright/profiles_settings.xml ================================================ ================================================ FILE: .idea/encodings.xml ================================================ ================================================ FILE: .idea/gradle.xml ================================================ ================================================ FILE: .idea/libraries/appcompat_v7_21_0_3.xml ================================================ ================================================ FILE: .idea/libraries/junit_3_8.xml ================================================ ================================================ FILE: .idea/libraries/play_services_6_1_71.xml ================================================ ================================================ FILE: .idea/libraries/support_annotations_21_0_3.xml ================================================ ================================================ FILE: .idea/libraries/support_v4_21_0_3.xml ================================================ ================================================ FILE: .idea/misc.xml ================================================ ================================================ FILE: .idea/modules.xml ================================================ ================================================ FILE: .idea/scopes/scope_settings.xml ================================================ ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: CONTRIBUTING ================================================ Contributing {#contributing} ============ Want to contribute? Great! First, read this page (including the small print at the end). # Before you contribute Before we can use your code, you must sign the [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1) (CLA), which you can do online. The CLA is necessary mainly because you own the copyright to your changes, even after your contribution becomes part of our codebase, so we need your permission to use and distribute your code. We also need to be sure of various other things—for instance that you'll tell us if you know that your code infringes on other people's patents. You don't have to sign the CLA until after you've submitted your code for review and a member has approved it, but you must do it before we can put your code into our codebase. Before you start working on a larger contribution, you should get in touch with us first through the issue tracker with your idea so that we can help out and possibly guide you. Coordinating up front makes it much easier to avoid frustration later on. # Code reviews All submissions, including submissions by project members, require review. We use Github pull requests for this purpose. # The small print Contributions made by corporations are covered by a different agreement than the one above, the Software Grant and Corporate Contributor License Agreement. ================================================ FILE: ExampleGame.iml ================================================ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: app/app.iml ================================================ ================================================ FILE: app/build.gradle ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion "19.1" defaultConfig { applicationId "com.google.fpl.gim.examplegame" minSdkVersion 16 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { } } repositories { mavenCentral() flatDir { dirs 'libs' } } dependencies { compile group: 'junit', name: 'junit', version: '3.8' compile 'com.android.support:appcompat-v7:21.+' compile 'com.google.android.gms:play-services:6.1.+' } ================================================ FILE: app/src/androidTest/java/com/google/fpl/gim/examplegame/MissionParseTest.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import com.google.fpl.gim.examplegame.utils.MissionParseException; import com.google.fpl.gim.examplegame.utils.MissionParser; import com.google.fpl.gim.examplegame.utils.Utils; import junit.framework.Assert; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.InputStream; /** * Tests the functionality of mission parsing from XML. */ public class MissionParseTest extends TestCase { private static final String TAG = MissionParseTest.class.getSimpleName(); private Mission mMission; private MissionData mMissionData; public void setUp() { Utils.logDebug(TAG, "Setting up..."); // Set up mission data that will be used for every test case String missionId = "Mission 1"; float lengthOfGameMinutes = 30f; // 30-minute game float lengthOfIntervalMinutes = 1f; // 1-minute intervals float challengePaceMinutesPerMile = 8.0f; mMissionData = new MissionData(missionId, missionId, lengthOfGameMinutes, lengthOfIntervalMinutes, challengePaceMinutesPerMile); } public void tearDown() { Utils.logDebug(TAG, "Tearing down..."); } /** * Test for correct construction of a timer moment. */ public void testTimerMomentConstruction() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createTimerMomentXml( // [...] "start", // Moment id. "start", // Next moment id. 0.5); // Length of timer moment (minutes). // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); } Assert.assertEquals("Mission 1", mMissionData.getMissionId()); Assert.assertEquals(1, mMissionData.getNumMoments()); Assert.assertEquals(true, mMissionData.getMomentFromId("start") instanceof TimerMoment); Assert.assertEquals("start", mMissionData.getMomentFromId("start").getNextMomentId()); } /** * Test for correct construction of a choice moment. */ public void testChoiceMomentConstruction() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createStartChoiceMomentXml( // [...] "start", // Moment id. 0.5, // Length of choice timeout in minutes. "Example ChoiceMoment Description", // Description of choice moment. "choice_2"); // Id of default choice. xml += createChoiceXml( // [...] "fire", // Choice id. "Example Choice Description 1", // Description of choice. "start", // Next moment id. true, // Whether the weapon charge should be depleted false, // Whether the number of enemies defeated should // be incremented. "test_icon"); // Icon resource name. // xml += createChoiceXml( // [...] "choice_2", // Choice id. "Example Choice Description 2", // Description of choice. "start", // Next moment id. false, // Whether the weapon charge should be depleted false, // Whether the number of enemies defeated should // be incremented. "test_icon"); // Icon resource name. // xml += createChoiceXml( // [...] "choice_3", // Choice id. "Example Choice Description 3", // Description of choice. "start", // Next moment id. true, // Whether the weapon charge should be depleted false, // Whether the number of enemies defeated should // be incremented. "test_icon"); // Icon resource name. // xml += createEndChoiceMomentXml(); // xml += createEndMissionXml(); // Utils.logDebug(TAG, xml); InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); } Assert.assertEquals("Mission 1", mMissionData.getMissionId()); Assert.assertEquals(1, mMissionData.getNumMoments()); Assert.assertEquals(true, mMissionData.getMomentFromId("start") instanceof ChoiceMoment); ChoiceMoment choiceMoment = ((ChoiceMoment) mMissionData.getMomentFromId("start")); Assert.assertEquals(3, choiceMoment.getMomentData().getNumChoices()); Choice choice1 = choiceMoment.getMomentData().getChoiceById("choice_2"); Assert.assertEquals("Example Choice Description 2", choice1.getDescription()); Assert.assertEquals("start", choice1.getNextMomentId()); Assert.assertEquals(false, choice1.getOutcome().weaponChargeDepleted()); Assert.assertEquals(false, choice1.getOutcome().numEnemiesDefeatedIncremented()); Assert.assertEquals("test_icon", choice1.getDrawableResourceName()); Assert.assertEquals(null, mMissionData.getMomentFromId("start").getNextMomentId()); } /** * Test for correct construction of an sfx moment. */ public void testSfxMomentConstruction() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createSfxMomentXml( // [...] "start", // Moment id. "start", // Next moment id. "path/to/something"); // Path to sound effect resource. // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); } Assert.assertEquals("Mission 1", mMissionData.getMissionId()); Assert.assertEquals(1, mMissionData.getNumMoments()); Assert.assertEquals(true, mMissionData.getMomentFromId("start") instanceof SfxMoment); Assert.assertEquals("start", mMissionData.getMomentFromId("start").getNextMomentId()); } /** * Test for correct construction of a spoken text moment. */ public void testSpokenTextMomentConstruction() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createSpokenTextMomentXml( // [...] "start", // Moment id. "start", // Next moment id. "Hello!"); // Text to speak out loud. // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); } Assert.assertEquals("Mission 1", mMissionData.getMissionId()); Assert.assertEquals(1, mMissionData.getNumMoments()); Assert.assertEquals(true, mMissionData.getMomentFromId("start") instanceof SpokenTextMoment); Assert.assertEquals("start", mMissionData.getMomentFromId("start").getNextMomentId()); } /** * Test for correct construction of a mission with four different types of moments. */ public void testFourMomentConstruction() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createSpokenTextMomentXml( // [...] "start", // Moment id. "second", // Next moment id. "Hello!"); // Text to speak out loud. // xml += createSfxMomentXml( // [...] "second", // Moment id. "third", // Next moment id. "path/to/something"); // Path to sound effect resource. // xml += createStartChoiceMomentXml( // [...] "third", // Moment id. 0.5, // Length of choice timeout in minutes. "Example ChoiceMoment Description", // Description of choice moment. "choice_2"); // Id of default choice. xml += createChoiceXml( // [...] "fire", // Choice id. "Example Choice Description 1", // Description of choice. "fourth", // Next moment id. true, // Whether the weapon charge should be depleted false, // Whether the number of enemies defeated should // be incremented. "test_icon"); // Icon resource name. // xml += createChoiceXml( // [...] "choice_2", // Choice id. "Example Choice Description 2", // Description of choice. "fourth", // Next moment id. false, // Whether the weapon charge should be depleted false, // Whether the number of enemies defeated should // be incremented. "test_icon"); // Icon resource name. // xml += createEndChoiceMomentXml(); // xml += createTimerMomentXml( // [...] "fourth", // Moment id. null, // Next moment id. 0.25); // Length of timer moment (minutes). // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); } Assert.assertEquals("Mission 1", mMissionData.getMissionId()); Assert.assertEquals(4, mMissionData.getNumMoments()); Moment spokenTextMoment = mMissionData.getMomentFromId("start"); Moment sfxMoment = mMissionData.getMomentFromId("second"); Moment choiceMoment = mMissionData.getMomentFromId("third"); Moment timerMoment = mMissionData.getMomentFromId("fourth"); Assert.assertEquals(true, spokenTextMoment instanceof SpokenTextMoment); Assert.assertEquals(true, sfxMoment instanceof SfxMoment); Assert.assertEquals(true, choiceMoment instanceof ChoiceMoment); Assert.assertEquals(true, timerMoment instanceof TimerMoment); SpokenTextMoment moment1 = (SpokenTextMoment) spokenTextMoment; SfxMoment moment2 = (SfxMoment) sfxMoment; ChoiceMoment moment3 = (ChoiceMoment) choiceMoment; TimerMoment moment4 = (TimerMoment) timerMoment; Assert.assertEquals("second", moment1.getNextMomentId()); Assert.assertEquals("third", moment2.getNextMomentId()); // The next ID of a ChoiceMoment is null until the user has made their choice. Assert.assertEquals(null, moment3.getNextMomentId()); Assert.assertEquals("fourth", moment3.getMomentData().getChoices()[0].getNextMomentId()); // The final moment has a 'null' next moment. Assert.assertEquals(null, moment4.getNextMomentId()); Assert.assertEquals(true, moment3.getMomentData().getChoiceById("fire") .requiresChargedWeapon()); Assert.assertEquals(false, moment3.getMomentData().getChoiceById("choice_2") .requiresChargedWeapon()); } /** * Test for correct error handling with a moment has an invalid 'type'. */ public void testMomentWithInvalidTypeErrorHandling() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createStartMomentXml( // [...] "invalid", // Moment type is invalid. "start"); // Moment id. xml += createNextMomentXml("start"); // Next moment id. xml += createLengthMinutesXml(0.25); // Length of (timer) moment in minutes. xml += createEndMomentXml(); // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); boolean didMissionParseFail = false; try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { didMissionParseFail = true; } Assert.assertEquals(true, didMissionParseFail); } /** * Test for correct error handling with a moment has no 'type' attribute. */ public void testMomentWithNoTypeErrorHandling() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += " [...] "id='start' >"; // Moment id. Moment type is missing. xml += createNextMomentXml("start"); // Next moment id. xml += createLengthMinutesXml(0.25); // Length of (timer) moment in minutes. xml += createEndMomentXml(); // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); boolean didMissionParseFail = false; try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { didMissionParseFail = true; } Assert.assertEquals(true, didMissionParseFail); } /* * Test for correct behavior when a moment has no 'next_moment' attribute (signifies that this * moment is the final moment in the mission.) */ public void testTimerMomentMissingNextMomentMission() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Name of mission. xml += createStartMomentXml( // [...] "timer", // Moment type. "start"); // Moment id. xml += createLengthMinutesXml(0.25); // Length of (timer) moment in minutes. xml += createEndMomentXml(); // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); } Assert.assertEquals("Mission 1", mMissionData.getMissionId()); Assert.assertEquals(1, mMissionData.getNumMoments()); Assert.assertEquals(true, mMissionData.getMomentFromId("start") instanceof TimerMoment); Assert.assertEquals(null, mMissionData.getMomentFromId("start").getNextMomentId()); } /** * Test for correct reading of a mission name. */ public void testMissionNameConstruction() { String xml = ""; xml += createStartMissionXml( // [...] "", // First moment in mission. "Name"); // Mission name. xml += createEndMissionXml(); // InputStream missionInputStream = new ByteArrayInputStream(xml.getBytes()); String missionName = null; try { missionName = MissionParser.getMissionName(missionInputStream); } catch (MissionParseException e) { e.printStackTrace(); } Assert.assertEquals("Name", missionName); } /** * Test for correct error handling for a mission with no "name" attribute. */ public void testMissingMissionNameHandling() { String xml = ""; xml += " [...] "start_id='' >"; // First moment in mission. Mission name is // missing. xml += createEndMissionXml(); // InputStream missionInputStream = new ByteArrayInputStream(xml.getBytes()); boolean didMissionNameParseFail = false; try { MissionParser.getMissionName(missionInputStream); } catch (MissionParseException e) { didMissionNameParseFail = true; } Assert.assertEquals(true, didMissionNameParseFail); } /** * Test for correct parsing of fictional progress for a SpokenText moment. */ public void testFictionalProgressSpokenTextMomentParsing() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createSpokenTextMomentWithFictionalProgressXML( // [...] "start", // Moment id. null, // Next moment id. "Text to speak", // Text to speak out loud. "Fictional progress."); // Fictional progress. // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); } Assert.assertEquals(1, mMissionData.getMomentFromId("start").getFictionalProgress().size()); Assert.assertEquals("Fictional progress.", mMissionData.getMomentFromId("start").getFictionalProgress().get(0)); } /** * Test for correct parsing of fictional progress for a Timer moment. */ public void testFictionalProgressTimerMomentParsing() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createTimerMomentWithFictionalProgressXML( // [...] "start", // Moment id. null, // Next moment id. 1.0, // Length of timer moment (minutes). "Fictional progress."); // Fictional progress. // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); } Assert.assertEquals(1, mMissionData.getMomentFromId("start").getFictionalProgress().size()); Assert.assertEquals("Fictional progress.", mMissionData.getMomentFromId("start").getFictionalProgress().get(0)); } /** * Test for correct parsing of fictional progress for an Sfx moment. */ public void testFictionalProgressSfxMomentParsing() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createSfxMomentWithFictionalProgressXML( // [...] "start", // Moment id. null, // Next moment id. "path/to/something", // Path to sound effect resource. "Fictional progress."); // Fictional progress. // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); } Assert.assertEquals(1, mMissionData.getMomentFromId("start").getFictionalProgress().size()); Assert.assertEquals("Fictional progress.", mMissionData.getMomentFromId("start").getFictionalProgress().get(0)); } /** * Test for correct parsing of fictional progress for a Choice moment, and for correct parsing * of fictional progress for Choices. */ public void testFictionalProgressChoiceMomentParsing() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createStartChoiceMomentWithFictionalProgressXML( // [...] "start", // Moment id. 1.0, // Next moment id. "Choice Description", // Description of choice moment. "choice_2", // Id of default choice. "Fictional progress."); // Fictional progress. xml += createChoiceWithFictionalProgressXML( // [...] "fire", // Choice id. "Example Choice Description 1", // Description of choice. null, // Next moment id. true, // Whether the weapon charge should be depleted. false, // Whether the number of enemies defeated should // be incremented. "Description 1", // Fictional progress. "test_icon"); // Icon resource name. // xml += createChoiceXml( // [...] "choice_2", // Choice id. "Choice 2 description", // Description of choice. null, // Next moment id. false, // Whether the weapon charge should be depleted. false, // Whether the number of enemies defeated should // be incremented. "test_icon"); // Icon resource name. // xml += createEndMomentXml(); // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); } ChoiceMoment choiceMoment = ((ChoiceMoment) mMissionData.getMomentFromId("start")); Choice fireChoice = choiceMoment.getMomentData().getChoiceById("fire"); Assert.assertEquals(1, fireChoice.getFictionalProgress().size()); Assert.assertEquals("Description 1", fireChoice.getFictionalProgress().get(0)); Choice choice2 = choiceMoment.getMomentData().getChoiceById("choice_2"); Assert.assertEquals(0, choice2.getFictionalProgress().size()); Assert.assertEquals(1, mMissionData.getMomentFromId("start").getFictionalProgress().size()); Assert.assertEquals("Fictional progress.", mMissionData.getMomentFromId("start").getFictionalProgress().get(0)); } /** * Test for correct error handling for a fictional progress element that is empty. */ public void testFictionalProgressErrorHandling() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createTimerMomentWithFictionalProgressXML( // [...] "start", // Moment id. null, // Next moment id. 1.0, // Length of timer moment (minutes). ""); // Empty fictional progress. // xml += createEndMissionXml(); // InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); boolean didMissionParseFail = false; try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { didMissionParseFail = true; } Assert.assertEquals(true, didMissionParseFail); } /** * Test for correct error handling for a Choice that has no icon element. */ public void testChoiceMissingIconErrorHandling() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createStartChoiceMomentXml( // [...] "start", // Moment id. 0.5, // Length of choice timeout in minutes. "Example ChoiceMoment Description", // Description of choice moment. "choice_2"); // Id of default choice. xml += createChoiceXml( // [...] "fire", // Choice id. "Example Choice Description 1", // Description of choice. "start", // Next moment id. true, // Whether the weapon charge should be depleted false, // Whether the number of enemies defeated should // be incremented. "test_icon"); // Icon resource name. // xml += createChoiceXml( // [...] "choice_2", // Choice id. "Example Choice Description 2", // Description of choice. "start", // Next moment id. false, // Whether the weapon charge should be depleted false, // Whether the number of enemies defeated should // be incremented. null); // Missing icon element. // xml += createEndChoiceMomentXml(); // xml += createEndMissionXml(); // Utils.logDebug(TAG, xml); InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); boolean didMissionParseFail = false; try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); didMissionParseFail = true; } Assert.assertEquals(true, didMissionParseFail); } /** * Test for correct error handling for a Choice that has an empty icon element. */ public void testChoiceEmptyIconErrorHandling() { String xml = ""; xml += createStartMissionXml( // [...] "start", // First moment in mission. "Name"); // Mission name. xml += createStartChoiceMomentXml( // [...] "start", // Moment id. 0.5, // Length of choice timeout in minutes. "Example ChoiceMoment Description", // Description of choice moment. "choice_2"); // Id of default choice. xml += createChoiceXml( // [...] "fire", // Choice id. "Example Choice Description 1", // Description of choice. "start", // Next moment id. true, // Whether the weapon charge should be depleted false, // Whether the number of enemies defeated should // be incremented. "test_icon"); // Icon resource name. // xml += createChoiceXml( // [...] "choice_2", // Choice id. "Example Choice Description 2", // Description of choice. "start", // Next moment id. false, // Whether the weapon charge should be depleted false, // Whether the number of enemies defeated should // be incremented. ""); // Empty icon resource name. // xml += createEndChoiceMomentXml(); // xml += createEndChoiceMomentXml(); // xml += createEndMissionXml(); // Utils.logDebug(TAG, xml); InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes()); mMission = new Mission(mMissionData); boolean didMissionParseFail = false; try { mMission.readMoments(momentInputStream); } catch (MissionParseException e) { e.printStackTrace(); didMissionParseFail = true; } Assert.assertEquals(true, didMissionParseFail); } /** * A helper function to create an XML string representing the start of a mission. * @param startMomentId The id of the first moment in the mission. * @param missionName The plain text name of the mission. * @return An XML string of the following format: * * */ private String createStartMissionXml(String startMomentId, String missionName) { return "" + ""; } /** * A helper function to create an XML string representing the end of a mission. * @return A mission XML end-tag: */ private String createEndMissionXml() { return ""; } /** * A helper function to create an XML string representing the start of a generic moment. * @param momentType The type of moment to be created. * @param momentId The unique id of this moment. * @return An XML string of the following format: * */ private String createStartMomentXml(String momentType, String momentId) { return ""; } /** * A helper function to create an XML string representing the end of a moment. * @return A moment XML end-tag: */ private String createEndMomentXml() { return ""; } /** * A helper function to create an XML string representing a timer moment. * @param momentId The unique id of the moment. * @param nextMomentId The id of the next moment if this choice is chosen. Can be null if this * moment is the last moment in the mission. * @param lengthMinutes The length of the timer moment in minutes. * @return An XML string of the following format: * * * [lengthMinutes] * */ private String createTimerMomentXml(String momentId, String nextMomentId, double lengthMinutes) { String xml = ""; xml += createStartMomentXml("timer", momentId); xml += createNextMomentXml(nextMomentId); xml += createLengthMinutesXml(lengthMinutes); xml += createEndMomentXml(); return xml; } /** * A helper function to create an XML string representing a 'next_moment id' attribute. * All moment types can have 'next_moment id''s, and the lack of a 'next_moment id' signifies * that the current moment is the last moment in the mission. * @param nextMomentId The id of the next moment if this choice is chosen. Can be null if this * moment is the last moment in the mission. * @return If 'nextMomentId' is null, return an empty string. Otherwise, an XML string of the * following format is returned: * */ private String createNextMomentXml(String nextMomentId) { if (nextMomentId == null) { return ""; } return ""; } /** * A helper function to create an XML string representing the start of a choice moment. * @param momentId The unique id of the moment. * @param timeoutLengthMinutes The length of time in minutes after which the default choice * should be chosen for the user. * @param choiceDescription A meaningful, human-readable description of the choice to be made, * which is most likely in the form of either a direct or indirect * question. * @param defaultChoiceId The id of the choice that should be chosen if the decision times out * before the user has chosen their own choice. * @return An XML string with the following format: * * [timeoutLengthMinutes] * [choiceDescription] * * */ private String createStartChoiceMomentXml(String momentId, double timeoutLengthMinutes, String choiceDescription, String defaultChoiceId) { String xml = ""; xml += createStartMomentXml("choice", momentId); xml += "" + Double.toString(timeoutLengthMinutes) + ""; xml += "" + choiceDescription + ""; xml += ""; return xml; } /** * A helper function to create an XML string representing a choice. Choices are found within * choice moments. * @param choiceId The id of the choice. * @param choiceDescription A meaningful, human-readable description of the choice. * @param nextMomentId The id of the next moment if this choice is chosen. Can be null if this * moment is the last moment in the mission. * @param depleteWeaponCharge Whether the user's weapon should be depleted if they select this * choice. * @param incrementNumEnemiesDefeated Whether the number of enemies defeated should be * incremented if the user selects this choice. * @param iconResourceName The name of the drawable resource for this choice action. * @return An XML string with the following format: * * [choiceDescription] * * * * */ private String createChoiceXml(String choiceId, String choiceDescription, String nextMomentId, boolean depleteWeaponCharge, boolean incrementNumEnemiesDefeated, String iconResourceName) { String xml = ""; xml += ""; xml += "" + choiceDescription + ""; xml += createNextMomentXml(nextMomentId); xml += ""; if (iconResourceName != null) { xml += createIconXML(iconResourceName); } xml += ""; return xml; } /** * A helper function to create an XML string representing the end of a choice moment. * @return A moment XML end-tag: */ private String createEndChoiceMomentXml() { return createEndMomentXml(); } /** * A helper function to create an XML string representing a spoken text moment. * @param momentId The unique id of this moment. * @param nextMomentId The id of the next moment in the mission. Can be null if this moment is * the last moment in the mission. * @param textToSpeak A string that should be spoken aloud as part of this moment. * @return An XML string with the following format: * * * [textToSpeak] * */ private String createSpokenTextMomentXml(String momentId, String nextMomentId, String textToSpeak) { String xml = ""; xml += createStartMomentXml("spoken_text", momentId); xml += createNextMomentXml(nextMomentId); xml += "" + textToSpeak + ""; xml += createEndMomentXml(); return xml; } /** * A helper function to create an XML string representing a sfx moment. * @param momentId The unique id of this moment. * @param nextMomentId The id of the next moment in the mission. Can be null if this moment is * the last moment in the mission. * @param pathToResource The absolute path to the sound resource to be played as part of this * moment. * @return An XML string with the following format: * * * [pathToResource] * */ private String createSfxMomentXml(String momentId, String nextMomentId, String pathToResource) { String xml = ""; xml += createStartMomentXml("sfx", momentId); xml += createNextMomentXml(nextMomentId); xml += "" + pathToResource + ""; xml += createEndMomentXml(); return xml; } /** * A helper function to create an XML string representing a timer moment's 'length_minutes' * element. * @param lengthMinutes The length of the timer moment in minutes. * @return An XML string with the following format: * [lengthMinutes] */ private String createLengthMinutesXml(double lengthMinutes) { return "" + Double.toString(lengthMinutes) + ""; } /** * A helper function to create an XML string representing a 'fictional_progress' element. * @param progressDescription The fictional progress made. * @return An XML string with the following format: * [progressDescription] */ private String createFictionalProgressXml(String progressDescription) { return "" + progressDescription + ""; } /** * A helper function to create an XML string representing an 'icon' element. * @param iconResourceName The name of the drawable resource for this choice action. * @return An XML string with the following format: * */ private String createIconXML(String iconResourceName) { return ""; } /** * A helper function to create an XML string representing a spoken text moment with fictional * progress. * @param momentId The unique id of this moment. * @param nextMomentId The id of the next moment in the mission. Can be null if this moment is * the last moment in the mission. * @param textToSpeak A string that should be spoken aloud as part of this moment. * @param progressDescription A string describing the fictional progress. * @return An XML string with the following format: * * * [textToSpeak] * [progressDescription] * */ private String createSpokenTextMomentWithFictionalProgressXML(String momentId, String nextMomentId, String textToSpeak, String progressDescription) { String xml = ""; xml += createStartMomentXml("spoken_text", momentId); xml += createNextMomentXml(nextMomentId); xml += "" + textToSpeak + ""; xml += createFictionalProgressXml(progressDescription); xml += createEndMomentXml(); return xml; } /** * A helper function to create an XML string representing a timer moment with fictional * progress. * @param momentId The unique id of the moment. * @param nextMomentId The id of the next moment if this choice is chosen. Can be null if this * moment is the last moment in the mission. * @param lengthMinutes The length of the timer moment in minutes. * @param progressDescription A string describing the fictional progress. * @return An XML string of the following format: * * * [lengthMinutes] * [progressDescription] * */ private String createTimerMomentWithFictionalProgressXML(String momentId, String nextMomentId, double lengthMinutes, String progressDescription) { String xml = ""; xml += createStartMomentXml("timer", momentId); xml += createNextMomentXml(nextMomentId); xml += createLengthMinutesXml(lengthMinutes); xml += createFictionalProgressXml(progressDescription); xml += createEndMomentXml(); return xml; } /** * A helper function to create an XML string representing a sfx moment with fictional progress. * @param momentId The unique id of this moment. * @param nextMomentId The id of the next moment in the mission. Can be null if this moment is * the last moment in the mission. * @param pathToResource The absolute path to the sound resource to be played as part of this * moment. * @param progressDescription A string describing the fictional progress. * @return An XML string with the following format: * * * [pathToResource] * [progressDescription] * */ private String createSfxMomentWithFictionalProgressXML(String momentId, String nextMomentId, String pathToResource, String progressDescription) { String xml = ""; xml += createStartMomentXml("sfx", momentId); xml += createNextMomentXml(nextMomentId); xml += "" + pathToResource + ""; xml += createFictionalProgressXml(progressDescription); xml += createEndMomentXml(); return xml; } /** * A helper function to create an XML string representing the start of a choice moment with * fictional progress. * @param momentId The unique id of the moment. * @param timeoutLengthMinutes The length of time in minutes after which the default choice * should be chosen for the user. * @param choiceDescription A meaningful, human-readable description of the choice to be made, * which is most likely in the form of either a direct or indirect * question. * @param defaultChoiceId The id of the choice that should be chosen if the decision times out * before the user has chosen their own choice. * @param progressDescription A string describing the fictional progress. * @return An XML string with the following format: * * [timeoutLengthMinutes] * [choiceDescription] * * [progressDescription] */ private String createStartChoiceMomentWithFictionalProgressXML (String momentId, double timeoutLengthMinutes, String choiceDescription, String defaultChoiceId, String progressDescription) { String xml = ""; xml += createStartChoiceMomentXml(momentId, timeoutLengthMinutes, choiceDescription, defaultChoiceId); xml += createFictionalProgressXml(progressDescription); return xml; } /** * A helper function to create an XML string representing a choice. Choices are found within * choice moments. Contains a piece of fictional progress. * @param choiceId The id of the choice. * @param choiceDescription A meaningful, human-readable description of the choice. * @param nextMomentId The id of the next moment if this choice is chosen. Can be null if this * moment is the last moment in the mission. * @param depleteWeaponCharge Whether the user's weapon should be depleted if they select this * choice. * @param incrementNumEnemiesDefeated Whether the number of enemies defeated should be * incremented if the user selects this choice. * @param iconResourceName The name of the drawable resource for this choice action. * @return An XML string with the following format: * * [choiceDescription] * * * [progressDescription] * * */ private String createChoiceWithFictionalProgressXML(String choiceId, String choiceDescription, String nextMomentId, boolean depleteWeaponCharge, boolean incrementNumEnemiesDefeated, String progressDescription, String iconResourceName) { String xml = ""; xml += ""; xml += "" + choiceDescription + ""; xml += createNextMomentXml(nextMomentId); xml += ""; xml += createFictionalProgressXml(progressDescription); if (iconResourceName != null) { xml += createIconXML(iconResourceName); } xml += ""; return xml; } } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/assets/legacy_missions/choice_mission.xml ================================================ 0.5 What will you do? Fire!!! Use a sling shot. Drop a smoke bomb. 0.1 ================================================ FILE: app/src/main/assets/legacy_missions/mission.xml ================================================ 0.25 Created a mission. Made a timer moment 0.5 Example ChoiceMoment Description Example Choice Description 1 Fired a weapon. Example Choice Description 2 Example Choice Description 2 path/to/something Hello! ================================================ FILE: app/src/main/assets/legacy_missions/sfx mission.xml ================================================ You will now hear a snap sound. android.resource://com.google.fpl.gim.examplegame/raw/snap That was a snap! You're welcome. ================================================ FILE: app/src/main/assets/legacy_missions/spoken_plus_timer_mission.xml ================================================ This is the first moment in this mission. The next moment should be a timer moment lasting 6 seconds. 0.1 This is the final moment, and the previous moment lasted 6 seconds. ================================================ FILE: app/src/main/assets/legacy_missions/texttospeechmission.xml ================================================ Hello! Agent, your mission is simple. Good luck. Godspeed! ================================================ FILE: app/src/main/assets/legacy_missions/timermission.xml ================================================ 0.1 0.1 0.1 ================================================ FILE: app/src/main/assets/missions/01_sample_mission_1.xml ================================================ Welcome to Games In Motion! The year is 2012, and the apocalypse is upon us in the form of zombies. The zombies have decided that your brain looks particularly tasty, and a swarm is after you. You will be pursued relentlessly until you reach the base, which is approximately 3 minutes away by foot. You will be notified when a zombie begins to chase you, and you will have to react appropriately. Keep an eye on your wrist gadget, but don't run into any trees, or else the zombies will surely catch you. Good luck! Start running now! You have at least a minute before a zombie will begin to chase you. Started a mission Received instructions 3 You are now being chased! Your options are as follows: Number 1. Act like a zombie in order to blend in. Number 2. Throw an axe at the zombie. Make your choice using your mobile device. Choose wisely. Encountered a zombie 0.5 What will you do? Fire!!! Axe. Threw an axe. Blend. Pretended to be a zombie android.resource://com.google.fpl.gim.examplegame/raw/axe android.resource://com.google.fpl.gim.examplegame/raw/brains You defeated the zombie! Good thing because Killed the zombie! You were caught! That's okay because Failed at pretending to be a zombie. You have arrived at the base. Arrived at the base. ================================================ FILE: app/src/main/assets/missions/02_sample_mission_2.xml ================================================ Hello Agent. Welcome to Games In Motion! The year is 2012, and the apocalypse is upon us in the form of zombies. Your task is to make it to our base. But the zombies have decided that your brain looks particularly tasty, and a swarm is after you. You will be pursued relentlessly until you reach the base, which is approximately 20 minutes away by foot. Keep an eye on your wrist gadget: you will be notified when a zombie begins to chase you, and you will have to react appropriately. Don’t run into any trees, or else the zombies will surely catch you. We’ve provided you with a simple super charger. Run faster, and you’ll get a shot to use against the zombies. Good luck! Start running now! You have at least a minute before a zombie will begin to chase you. Agent: Apocalypse 3.0 Watch out, there is a zombie behind you! Look at your wrist gadget and act quickly to defeat the them. If you’ve got a shot, you can take it. Otherwise, you can act like a zombie in order to blend in. Or, throw an axe at the zombie. Choose wisely. 0.5 Face the first zombie! Fire!!! Axe. Blend. android.resource://com.google.fpl.gim.examplegame/raw/fire android.resource://com.google.fpl.gim.examplegame/raw/axe android.resource://com.google.fpl.gim.examplegame/raw/brains Right in the eye! Nice work, agent. You just might have this zombie thing down. Hum. I did not expect that to work. Well, keep it up! Why on earth did you think blending in would work? You barely got out of that! You’ll never be a great agent if you act like that. 3.0 3.0 All right agent, I have a real task for you now. How would you like a chance to redeem yourself? There’s a fork in the road ahead. We have intel suggesting that a zombie mans the split. One of the paths leads to a bunker, and that bunker has a hard drive we need you to get. Don’t worry if you can’t find it right away - but know that the zombie may pursue if you get their attention. If you take care of them quickly, they might have something on their person. Or is it just a body since they are dead? Undead? Anyway, it will tell you where to go. 0.5 Fork in the road Fire!!! Left - sneak Right - sneak android.resource://com.google.fpl.gim.examplegame/raw/fire android.resource://com.google.fpl.gim.examplegame/raw/sneak Well done. And I was right, of course. The zombie had a slip of paper saying to go left. Head down the path. It will be obvious when you get there. You certainly have his attention now. How disappointing. And, and, what are you doing? Do you really think jumping into the bramble will help you here? You're just making noise. Perhaps if you're extraordinarily lucky, you can lose the zombie on your tail. Sigh. Now I have to make contingency plans to recover that hard drive, all because of your stupidity. 3.0 3.0 Right time, right location. I like your consistency, agent. Much better than the other candidates we were investigating. You are doing so well that I apologize for the pedantic explanation of your next task. I am in shock at your luck. How did you lose that zombie? I swear they were following you the entire time. And how did you find the bunker after all that? You do realize that good luck does not a good agent make? But as long as you are here, you might as well be useful. Go inside, go downstairs, turn left. 3 doors down will be a room labeled Animatrix. You'll need to break the window, get in, and grab the blue external hard drive next to the large computer. You will lose contact in there, but I will check in again once you get out. 3.0 You got out. By the way, there is a horde of zombies chasing you. Why aren’t you running now? Didn’t I warn you about them? We saw them on the radar nearly 10 minutes ago. Oh well. Better late than never I suppose. Start running now! 3.0 You are at the base now, but the horde is still chasing you. The horde is thinner now, but we can’t let you in until you defeat them. Our own safety is much more important than yours, after all. Deal with them. Or we will deal with you. 0.5 The horde is here. Fire!!! Join them. Jetpack! android.resource://com.google.fpl.gim.examplegame/raw/fire android.resource://com.google.fpl.gim.examplegame/raw/brains android.resource://com.google.fpl.gim.examplegame/raw/jetpack I suppose that firing like a maniac into a horde of zombies is one way to go. Shockingly, you were successful. I guess that means we have to let you in now. Darn it. Well, you completed the mission, so you are now an agent. I begrudgingly offer my congratulations. You have decided to join them? How rude. Needless to say, you did not complete the mission, and your agent status has been revoked. We might consider granting it to you again, but not until you return for your next mission. Farewell. Where did that jetpack come from? And how inconsiderate of you to leave us behind to deal with the horde. Needless to say, you did not complete the mission, and your agent status has been revoked. We might consider granting it to you again, but not until you return for your next mission. Farewell. Mission end. ================================================ FILE: app/src/main/assets/missions/ex_01_timer_moment.xml ================================================ 0.5 Played a mission! Played a timer moment ================================================ FILE: app/src/main/assets/missions/ex_02_spoken_text_moment.xml ================================================ Hello! This is a spoken text moment that uses text to speech. Heard a spoken text moment ================================================ FILE: app/src/main/assets/missions/ex_03_choice_moment.xml ================================================ 0.5 What will you do? Made a choice Fire!!! Use a sling shot. Used a slingshot Drop a smoke bomb. Used a smoke bomb ================================================ FILE: app/src/main/assets/missions/ex_04_sfx_moment.xml ================================================ android.resource://com.google.fpl.gim.examplegame/raw/brains BRAINS BRAINS BRAINS BRAINS BRAAAAAAAAAAAAAAAINS ================================================ FILE: app/src/main/assets/missions/ex_05_broken_timer_moment.xml ================================================ Played a mission! Played a timer moment ================================================ FILE: app/src/main/assets/missions/ex_06_long_timer_mission.xml ================================================ 100.0 ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/Choice.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import java.util.ArrayList; /** * Describes an option that a user has when presented with a decision to make. * Choices are only meaningful when there are 2+ of them. */ public class Choice { // Unique identifier for this Choice. private String mChoiceId; // The description of this option. private String mDescription; // The moment to go to next. private String mNextMomentId; // The set of changes to make if the player chooses this option. private Outcome mOutcome; // Whether or not this Choice requires a charged weapon. private boolean mRequiresChargedWeapon; // Fictional Progress associated with this choice. private ArrayList mFictionalProgress; // The name of the resource icon to display for this Choice's action. private String mDrawableResourceName; public Choice(String choiceId, String text, String nextMomentId, Outcome outcome, boolean requiresChargedWeapon, ArrayList fictionalProgress, String drawableResourceName) { mChoiceId = choiceId; mDescription = text; mNextMomentId = nextMomentId; mOutcome = outcome; mRequiresChargedWeapon = requiresChargedWeapon; mFictionalProgress = fictionalProgress; mDrawableResourceName = drawableResourceName; } public String getChoiceId() { return mChoiceId; } public String getDescription() { return mDescription; } public String getNextMomentId() { return mNextMomentId; } public Outcome getOutcome() { return mOutcome; } public ArrayList getFictionalProgress() { return mFictionalProgress; } public boolean requiresChargedWeapon() { return mRequiresChargedWeapon; } public String getDrawableResourceName() { return mDrawableResourceName; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/ChoiceMoment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import com.google.fpl.gim.examplegame.gui.NotificationOptions; import com.google.fpl.gim.examplegame.utils.Utils; import java.util.ArrayList; /** * Describes a Moment in which the user is presented with a decision to make. */ public class ChoiceMoment extends Moment { private static final String TAG = ChoiceMoment.class.getSimpleName(); public static final int MAXIMUM_NUM_OF_CHOICES = 3; public static final int MINIMUM_NUM_OF_CHOICES = 2; private static final String CHOICE_NOTIFICATION_ACTION_1 = "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_1"; private static final String CHOICE_NOTIFICATION_ACTION_2 = "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_2"; private static final String CHOICE_NOTIFICATION_ACTION_3 = "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_3"; private static final String CHOICE_ID_KEY = "com.google.fpl.gim.examplegame.CHOICE_ID_KEY"; private static final String ICON_RESOURCE_FOLDER = "drawable"; private static long[] VIBRATE_PATTERN = {0, 300, 100, 300, 100, 300}; private ChoiceMomentData mData; private long mStartTimeNanos; private Choice mSelectedChoice = null; public ChoiceMoment (Mission mission, ChoiceMomentData data) { super(mission); this.mData = data; } public void update(long nowNanos) { Utils.logDebug(TAG, "ChoiceMoment \"" + mData.getMomentId() + "\" update."); if (!isDone() && hasTimeToMakeChoiceExpired(nowNanos)) { // Pick default choice if (noChoiceSelectedYet()) { selectChoice(mData.getDefaultChoiceId()); } setIsDone(true); } } @Override public void start(long nowNanos) { super.start(nowNanos); Utils.logDebug(TAG, "ChoiceMoment \"" + mData.getMomentId() + "\" started."); setStartTimeNanos(nowNanos); // If the user's weapon is not charged, the choice to fire their weapon should not be // displayed. Choice[] choices = mData.getChoices(); int numActions = mData.getNumChoices(); if (!getMission().isWeaponCharged()) { numActions--; } // Create notification actions using the valid choices. NotificationCompat.Action[] actions = new NotificationCompat.Action[numActions]; int index = 0; String[] allActions = {CHOICE_NOTIFICATION_ACTION_1, CHOICE_NOTIFICATION_ACTION_2, CHOICE_NOTIFICATION_ACTION_3}; for (Choice choice : choices) { if (!choice.requiresChargedWeapon() || getMission().isWeaponCharged()) { // Bounds checked in MissionParser.java, which requires each choice moment to have // 2 or 3 choices associated with it. Intent actionIntent = new Intent(allActions[index]); actionIntent.putExtra(CHOICE_ID_KEY, choice.getChoiceId()); String resourceName = choice.getDrawableResourceName(); String packageName = getMission().getService().getPackageName(); int resource = getMission().getService().getResources() .getIdentifier(resourceName, ICON_RESOURCE_FOLDER, packageName); // If the resource does not exist, default to using application icon. if (resource == 0) { resource = getMission().getService().getApplicationInfo().icon; } actions[index] = getMission().getService() .makeNotificationAction(actionIntent, resource, choice.getDescription()); index++; } } // Create the notification to warn the user of an approaching enemy. NotificationOptions notificationOptions = NotificationOptions.getDefaultNotificationOptions(); notificationOptions.setNotificationId(MainService.CHOICE_NOTIFICATION_ID); notificationOptions.setPriorityAsMax(); notificationOptions.setActions(actions); notificationOptions.setNotificationDefaults(0); notificationOptions.setVibratePattern(VIBRATE_PATTERN); getMission().getService().postActionNotification(notificationOptions); } @Override public void end() { Utils.logDebug(TAG, "ChoiceMoment \"" + mData.getMomentId() + "\" ended."); // Remove choice notification. dismissNotification(); } /** * The next moment is not defined for a ChoiceMoment until the user has selected a choice. * @return Returns null until a choice is made, then returns the nextMomentId. */ @Override public String getNextMomentId() { if (mSelectedChoice == null) { return null; } else { return mSelectedChoice.getNextMomentId(); } } @Override public void restart(long nowNanos) { start(nowNanos); } public ChoiceMomentData getMomentData() { return this.mData; } public void setStartTimeNanos(long startTimeNanos) { this.mStartTimeNanos = startTimeNanos; } public boolean hasTimeToMakeChoiceExpired(long nowNanos) { return (nowNanos - mStartTimeNanos) >= Utils.minutesToNanos(mData .getTimeoutLengthMinutes()); } public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(CHOICE_NOTIFICATION_ACTION_1) || intent.getAction().equals(CHOICE_NOTIFICATION_ACTION_2) || intent.getAction().equals(CHOICE_NOTIFICATION_ACTION_3)) { String choiceId = intent.getStringExtra(CHOICE_ID_KEY); selectChoice(choiceId); } } public synchronized void selectChoice(String choiceId) { if (!isDone()) { Utils.logDebug(TAG, "Choice with id \"" + choiceId + "\" selected."); mSelectedChoice = mData.getChoiceById(choiceId); getMission().applyOutcome(mSelectedChoice.getOutcome()); setIsDone(true); } } public void dismissNotification() { NotificationManager notificationManager = (NotificationManager) getMission().getService() .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(MainService.CHOICE_NOTIFICATION_ID); } public boolean noChoiceSelectedYet() { return mSelectedChoice == null; } @Override public ArrayList getFictionalProgress() { ArrayList progress = new ArrayList<>(); progress.addAll(mData.getFictionalProgress()); if (!noChoiceSelectedYet()) { progress.addAll(mSelectedChoice.getFictionalProgress()); } return progress; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/ChoiceMomentData.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import java.util.ArrayList; import java.util.HashMap; /** * Encapsulates the data that is needed to define a unique ChoiceMoment. */ public class ChoiceMomentData extends MomentData { // The text describing the choice the player must make. private final String mDescription; // All of the choices that the user can have. private final HashMap mChoices; // Identifies the default Choice to execute in the case of a timeout. private final String mDefaultChoiceId; // Time in minutes until the default Choice is executed. private final float mTimeoutLengthMinutes; /** * Constructor to explicitly set all fields for a ChoiceMomentData. * @param momentId Identifier for the ChoiceMoment. * @param fictionalProgress Fictional progress for this moment. * @param description Text description for the decision to be made. * @param choices HashMap of Choices available to choose. * @param defaultChoiceId Default Choice in case of timeout. * @param timeoutLengthMinutes Length of time until timeout. */ public ChoiceMomentData(String momentId, ArrayList fictionalProgress, String description, HashMap choices, String defaultChoiceId, float timeoutLengthMinutes) { super(momentId, null, fictionalProgress); mDescription = description; mChoices = choices; mDefaultChoiceId = defaultChoiceId; mTimeoutLengthMinutes = timeoutLengthMinutes; } /** * Constructor for information from XML. * @param momentId Identifier for the ChoiceMoment. * @param fictionalProgress Fictional progress for this moment. * @param description Text description for the decision to be made. * @param defaultChoiceId Default Choice in case of timeout. * @param timeoutLengthMinutes Length of time until timeout. */ public ChoiceMomentData(String momentId, ArrayList fictionalProgress, String description, String defaultChoiceId, float timeoutLengthMinutes) { this(momentId, fictionalProgress, description, new HashMap(), defaultChoiceId, timeoutLengthMinutes); } public String getText() { return mDescription; } public Choice[] getChoices() { return mChoices.values().toArray(new Choice[mChoices.size()]); } public Choice getChoiceById(String choiceId) { return mChoices.get(choiceId); } public int getNumChoices() { return mChoices.size(); } public void addChoice(Choice choice) { mChoices.put(choice.getChoiceId(), choice); } public String getDefaultChoiceId() { return mDefaultChoiceId; } public float getTimeoutLengthMinutes() { return mTimeoutLengthMinutes; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/MainActivity.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import android.app.Fragment; import android.app.FragmentManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.google.fpl.gim.examplegame.gui.FitnessDataDisplayFragment; import com.google.fpl.gim.examplegame.gui.GameViews; import com.google.fpl.gim.examplegame.gui.NotificationOptions; import com.google.fpl.gim.examplegame.google.GoogleApiClientWrapper; import com.google.fpl.gim.examplegame.utils.Utils; import java.util.ArrayList; /** * MainActivity class on the UI thread. It has a game handler for the game loop to execute on. */ public class MainActivity extends ActionBarActivity { private static final String TAG = MainActivity.class.getSimpleName(); // Defines the action the BroadcastReceiver will receive. public static final String ENABLE_BACK = "com.google.fpl.gim.examplegame.ENABLE_BACK"; public static final String MISSION_START = "com.google.fpl.gim.examplegame.MISSION_START"; public static final String MISSION_END = "com.google.fpl.gim.examplegame.MISSION_END"; private static final String UPDATE_FITNESS_STATS = "com.google.fpl.gim.examplegame.UPDATE_FITNESS_STATS"; private MainService mMainService; // Service that runs the game logic. private GameViews mGameViews; // Container for all UI fragments. // Defines behavior when binding and unbinding mMainService. private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder binder) { if (binder == null) { throw new IllegalArgumentException("IBinder passed to onServiceConnected was null"); } mMainService = ((MainService.MainBinder) binder).getService(); mMainService.ConnectGoogleFitApiClient(MainActivity.this); // Register Intent receivers after the service is bound; this ensures that the Activity // is listening to intents sent from the service. // Register the mReceiver with an intent filter for rendering requests. IntentFilter filter = new IntentFilter(); filter.addAction(ENABLE_BACK); filter.addAction(MISSION_START); filter.addAction(MISSION_END); registerReceiver(mReceiver, filter); // Render the mReceiver with an intent filter for displaying an updated num steps filter = new IntentFilter(); filter.addAction(UPDATE_FITNESS_STATS); registerReceiver(mReceiver, filter); } public void onServiceDisconnected(ComponentName className) { mMainService = null; } }; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Update the step display fragment to show the current number of steps that the user // has taken. if (intent.getAction().equals(UPDATE_FITNESS_STATS)) { if (mMainService != null) { FitnessDataDisplayFragment fitnessDataDisplayFragment = mGameViews.getFitnessDataDisplayFragment(); if (fitnessDataDisplayFragment.isVisible()) { fitnessDataDisplayFragment.setFitnessStats( mMainService.getCurrentMission()); } } } // Receives an intent that requests back button to be enabled. if (intent.getAction().equals(ENABLE_BACK)) { getFragmentManager().popBackStack(); } // Receives an intent that requests end summary screen to display due to a mission end. if (intent.getAction().equals(MISSION_START)) { displayFitnessStats(); } // Receives an intent that requests end summary screen to display due to a mission end. if (intent.getAction().equals(MISSION_END)) { checkDisplayEndScreen(); } } }; @Override public void onDestroy() { Utils.logDebug(TAG, "onDestroy"); super.onDestroy(); if (isFinishing()) { // Stop the service from running in the background if the app exits. Intent intent = new Intent(this, MainService.class); intent.setPackage(getPackageName()); stopService(intent); } } @Override 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; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == android.R.id.home) { getFragmentManager().popBackStack(); } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == GoogleApiClientWrapper.REQUEST_CODE_OAUTH) { if (resultCode == RESULT_OK) { // If the user authenticated, try to connect again mMainService.userAuthenticated(); mMainService.reconnectGoogleApi(); } else { // Ideally there's a fail case here, handled by our own UX flow. // Keeping it empty for the sample. } } } /** * Responsible for transitioning from the start menu UI to the mission selection menu UI * @param view The view that is invoking this method. */ public void onStartButtonPressed(View view) { mGameViews.getStartMenuFragment().onStartButtonPressed(); } public void onEnterPressed(View view) { mGameViews.getRunSpecificationsFragment().onEnterPressed(); } public void onStartMissionPressed(View view) { // Get user selected run and mission information. String missionName = getGameViews().getListOfMissionsFragment().getSelectedMissionName(); String assetPath = getGameViews().getListOfMissionsFragment().getSelectedAssetPath(); float missionLengthMinutes = getGameViews().getRunSpecificationsFragment().getSelectedMissionLengthMinutes(); float intervalLengthMinutes = getGameViews().getRunSpecificationsFragment().getSelectedIntervalLengthMinutes(); float challengePaceMinutesPerMile = getGameViews().getRunSpecificationsFragment().getSelectedChallengePaceMinutesPerMile(); loadAndStartMission(assetPath, missionName, missionLengthMinutes, intervalLengthMinutes, challengePaceMinutesPerMile); // Disable the button and show that we are registering sensors. getGameViews().getMusicSelectionFragment().disableReadyButton(); } private void displayFitnessStats() { String missionName = getGameViews().getListOfMissionsFragment().getSelectedMissionName(); Fragment stepDisplayFragment = getGameViews().getFitnessDataDisplayFragment(); ((FitnessDataDisplayFragment)stepDisplayFragment).setMissionName(missionName); Fragment musicSelectionFragment = getGameViews().getMusicSelectionFragment(); getFragmentManager().beginTransaction() .setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left) .remove(musicSelectionFragment) .add(R.id.container, stepDisplayFragment, GameViews.FITNESS_DATA_DISPLAY_TAG) .addToBackStack(null) .commit(); getFragmentManager().executePendingTransactions(); // Disable home/back button on action bar. displayHomeUp(false); } public GameViews getGameViews() { return this.mGameViews; } public void loadAndStartMission(String missionFilePath, String missionName, float missionLength, float intervalLength, float challengePaceMinutesPerMile) { if (mMainService != null) { mMainService.loadAndStartMission(missionFilePath, missionName, missionLength, intervalLength, challengePaceMinutesPerMile); } } public void displayHomeUp(boolean display) { getSupportActionBar().setDisplayHomeAsUpEnabled(display); getSupportActionBar().setHomeButtonEnabled(display); } /** * Updates UI as Google Fit's connection status changes. */ public void onFitStatusUpdated(boolean connected) { // Hint to the fragments that might need to update their displays. mGameViews.getStartMenuFragment().onFitStatusUpdated(connected); mGameViews.getEndSummaryFragment().onFitStatusUpdated(connected); // End a mission or pop user back to start menu if we are disconnected. if (!connected) { if (mMainService != null && mMainService.isMissionRunning()) { // If a mission is running, end it. No different than a mission ending on its own. mMainService.endMission(); } else { // Jump back to the start screen. getFragmentManager().popBackStack(GameViews.START_MENU_TAG, 0); } if (mMainService != null) { // Post a notification. NotificationOptions notificationOptions = NotificationOptions.getDefaultNotificationOptions(); notificationOptions.setTitle(getResources().getString( R.string.disconnection_notification_title)); notificationOptions.setContent(getResources().getString( R.string.disconnection_notification_content)); notificationOptions.setNotificationId(MainService.FITNESS_DISCONNECT_NOTIFICATION_ID); notificationOptions.setPriorityAsHigh(); notificationOptions.setNotificationDefaults(NotificationCompat.DEFAULT_LIGHTS); mMainService.postActionNotification(notificationOptions); } } } @Override public void onBackPressed() { if (mMainService != null) { if (!mMainService.isMissionRunning() && canPressBackButton()) { // If not in a mission and not at the start, function like the in-app up button. getFragmentManager().popBackStack(); } else if (mMainService.isMissionRunning()) { // If a mission is running, end it. No different than a mission ending on its own. mMainService.endMission(); } else { // Will call finish() and end MainActivity. super.onBackPressed(); } } } public void setActionBarTitle(int string_res_id) { getSupportActionBar().setTitle(string_res_id); } public void setActionBarTitle(String title) { getSupportActionBar().setTitle(title); } @Override protected void onStart() { Utils.logDebug(TAG, "onStart"); super.onStart(); } @Override protected void onCreate(Bundle savedInstanceState) { Utils.logDebug(TAG, "onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Start service so it can run in bound and unbound state. Intent intent = new Intent(this, MainService.class); intent.setPackage(getPackageName()); startService(intent); // create new fragments and initialize data if (savedInstanceState == null) { mGameViews = new GameViews(); mGameViews.initializeFragments(this); } else { // restore old fragments and data mGameViews.restoreFragments(this); } displayHomeUp(canPressBackButton()); getFragmentManager().addOnBackStackChangedListener( new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { displayHomeUp(canPressBackButton()); } }); } @Override protected void onPause() { Utils.logDebug(TAG, "onPause"); super.onPause(); // Unregister all broadcasts before unbinding service. These will be registered again once // the onServiceConnected callback is called. This cannot be unregistered in the // onServiceConnected callback as MainActivity might be paused at that point, and it will // result in a crash. try { unregisterReceiver(mReceiver); } catch (IllegalArgumentException e) { Utils.logDebug(TAG, "Unable to unregister the Broadcast Receiver."); } // Unbind to allow service to run in the background. unbindService(mConnection); } @Override protected void onResume() { Utils.logDebug(TAG, "onResume"); super.onResume(); // Bind to the already running MainService so we can communicate with it. Intent intent = new Intent(this, MainService.class); intent.setPackage(getPackageName()); bindService(intent, mConnection, Context.BIND_WAIVE_PRIORITY); // Handles screen being asleep during run. Will display end screen if the run is over. checkDisplayEndScreen(); } @Override protected void onStop() { Utils.logDebug(TAG, "onStop"); super.onStop(); } /** * The back button should be active as long as there are fragment transactions in the back * stack. We always want the first fragment to be around so the back stack count needs to be * > 1. * @return Whether the back button should be active. */ private boolean canPressBackButton() { return getFragmentManager().getBackStackEntryCount() > 1; } private void checkDisplayEndScreen() { if (mMainService != null) { if (mMainService.shouldDisplayEndScreen()) { displayEndScreen(); } } } /** * Displays end run summary, with fictional and fitness results. */ private void displayEndScreen() { getFragmentManager().popBackStack(GameViews.START_MENU_TAG, 0); getFragmentManager().beginTransaction() .replace(R.id.container, mGameViews.getEndSummaryFragment(), GameViews.END_SUMMARY_TAG) .addToBackStack(null) .commit(); getFragmentManager().executePendingTransactions(); // Get results. ArrayList fictionalProgress = new ArrayList<>(); ArrayList fitnessResults = new ArrayList<>(); if (mMainService != null) { fictionalProgress.addAll(mMainService.getOverallFictionalProgress()); fitnessResults.addAll(mMainService.getFitnessStatistics()); } // Display results. mGameViews.getEndSummaryFragment().displayStats(fictionalProgress, fitnessResults); // Unlock first mission achievement if(mMainService.unlockAchievement(getString(R.string.ach_id_first_mission))) { Utils.logDebug(TAG, "Achievement Unlocked: First Mission"); } else { Utils.logDebug(TAG, "Warning: could not unlock achievement, not connected"); } if (mMainService != null) { mMainService.reset(); } displayHomeUp(true); } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/MainService.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import android.app.Activity; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.speech.tts.TextToSpeech; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.widget.Toast; import com.google.android.gms.games.Games; import com.google.fpl.gim.examplegame.gui.GameViews; import com.google.fpl.gim.examplegame.gui.NotificationOptions; import com.google.fpl.gim.examplegame.google.GoogleApiClientWrapper; import com.google.fpl.gim.examplegame.utils.MissionParseException; import com.google.fpl.gim.examplegame.utils.Utils; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.Locale; import java.util.Queue; /** * This is a Runnable for executing on the UI thread, and will add itself back * to the UI thread handler at the end of the run() function. * * While it will block the UI thread while running, it shouldn't block for that long. * We could always make a game thread if needed. */ public class MainService extends Service implements Runnable, MediaPlayer.OnCompletionListener { private final IBinder mBinder = new MainBinder(); private static final String TAG = MainService.class.getSimpleName(); private static final String CHOICE_NOTIFICATION_ACTION_1 = "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_1"; private static final String CHOICE_NOTIFICATION_ACTION_2 = "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_2"; private static final String CHOICE_NOTIFICATION_ACTION_3 = "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_3"; // Ids for notifications. public static final int CHOICE_NOTIFICATION_ID = 1; public static final int FITNESS_STATS_NOTIFICATION_ID = 2; public static final int FITNESS_DISCONNECT_NOTIFICATION_ID = 3; private static final Locale DEFAULT_TEXT_TO_SPEECH_LOCALE = Locale.UK; private Mission mMission; // The mission being played. Has reference to current game state. private static final long DELAY_MILLIS = 1000; // Time between updates, used as Handler delay. private Handler mUpdateHandler = new Handler(); // Audio related modules. private TextToSpeech mTextToSpeech; private boolean mIsTextToSpeechReady = false; private AudioManager mAudioManager; private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener; private MediaPlayer mMediaPlayer; // A queue of Audio Uris to be played. private class AudioQueueItem{ Uri mUri; MediaPlayer.OnCompletionListener mListener; AudioQueueItem(Uri uri, MediaPlayer.OnCompletionListener listener) { mUri = uri; mListener = listener; } @Override public boolean equals(Object o) { if (getClass() != o.getClass()) return false; AudioQueueItem audioQueueItem = (AudioQueueItem) o; return (mUri.equals(audioQueueItem.mUri)); } } private Queue mAudioQueue = new LinkedList<>(); private enum State { UNINITIALIZED, MISSION_LOADED, MISSION_RUNNING, END_SCREEN } private State mState = State.UNINITIALIZED; private GoogleApiClientWrapper mGoogleApiClientWrapper = new GoogleApiClientWrapper(); // Container for the GoogleApiClient private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (mMission != null && mMission.getMissionData().getCurrentMoment() != null) { // Choice moment handles choice selection. ((ChoiceMoment) mMission.getMissionData().getCurrentMoment()) .onReceive(context, intent); } } }; /** * This is the main game loop. Whenever it is done, it adds itself back to the handler. */ @Override public void run() { if (mState == State.MISSION_LOADED || mState == State.MISSION_RUNNING) { // This is where we can call the game state and the game logic. update(); } mUpdateHandler.postDelayed(this, DELAY_MILLIS); } public void userAuthenticated() { mGoogleApiClientWrapper.userAuthenticated(); } public void reconnectGoogleApi() { Utils.logDebug(TAG, "Reconnecting to Google API."); mGoogleApiClientWrapper.connect(); } public void ConnectGoogleFitApiClient(Activity activity) { mGoogleApiClientWrapper.buildGoogleApiClient(activity); mGoogleApiClientWrapper.connect(); } /** * Unlock a Play Games achievement. * * @param achievementId the ID of the achievement from the Google Play Developer Console, * @return true if Achievement unlocked, false otherwise. */ public boolean unlockAchievement(String achievementId) { if (mGoogleApiClientWrapper.isSignedIn()) { Games.Achievements.unlock(mGoogleApiClientWrapper.getGoogleApiClient(), achievementId); return true; } else { return false; } } /** * Loads and begins a mission. */ public void loadAndStartMission(String missionFilePath, String missionName, float missionLengthMinutes, float intervalLengthMinutes, float challengePaceMinutesPerMile) { if (!canEnterState(State.MISSION_LOADED)) { return; } MissionData data = new MissionData(missionName, missionFilePath, missionLengthMinutes, intervalLengthMinutes, challengePaceMinutesPerMile); mMission = new Mission(data); mMission.setService(this); // Open an InputStream from the given missionFileName. InputStream missionStream; try { missionStream = getAssets().open(missionFilePath); } catch (IOException e) { e.printStackTrace(); requestReselection(); return; } // Load the Moments. try { mMission.readMoments(missionStream); } catch (MissionParseException e) { e.printStackTrace(); requestReselection(); return; } try { missionStream.close(); } catch (IOException e) { e.printStackTrace(); } startMission(); } /** * Starts a mission. */ private void startMission() { setAndInitNextState(State.MISSION_LOADED); } /** * Ends a mission by halting updates. */ public void endMission() { setAndInitNextState(State.END_SCREEN); } @Override public void onCreate() { // The service is being created. Utils.logDebug(TAG, "onCreate"); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_1); intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_2); intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_3); registerReceiver(mReceiver, intentFilter); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // Determines the behavior for handling Audio Focus surrender. mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS) { if (mTextToSpeech.isSpeaking()) { mTextToSpeech.setOnUtteranceProgressListener(null); mTextToSpeech.stop(); } if (mMediaPlayer.isPlaying()) { mMediaPlayer.stop(); } // Abandon Audio Focus, if it's requested elsewhere. mAudioManager.abandonAudioFocus(mAudioFocusChangeListener); // Restart the current moment if AudioFocus was lost. Since AudioFocus is only // requested away from this application if this application was using it, // only Moments that play sound will restart in this way. if (mMission != null) { mMission.restartMoment(); } } } }; // Asynchronously prepares the TextToSpeech. mTextToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { // Check if language is available. switch (mTextToSpeech.isLanguageAvailable(DEFAULT_TEXT_TO_SPEECH_LOCALE)) { case TextToSpeech.LANG_AVAILABLE: case TextToSpeech.LANG_COUNTRY_AVAILABLE: case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE: Utils.logDebug(TAG, "TTS locale supported."); mTextToSpeech.setLanguage(DEFAULT_TEXT_TO_SPEECH_LOCALE); mIsTextToSpeechReady = true; break; case TextToSpeech.LANG_MISSING_DATA: Utils.logDebug(TAG, "TTS missing data, ask for install."); Intent installIntent = new Intent(); installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); startActivity(installIntent); break; default: Utils.logDebug(TAG, "TTS local not supported."); break; } } } }); mMediaPlayer = new MediaPlayer(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // The service is starting, due to a call to startService() Utils.logDebug(TAG, "onStartCommand"); return Service.START_STICKY; } @Override public IBinder onBind(Intent intent) { // A client is binding to the service with bindService() Utils.logDebug(TAG, "onBind"); return mBinder; } @Override public boolean onUnbind(Intent intent) { // All clients have unbound with unbindService() Utils.logDebug(TAG, "onUnbind"); return true; } @Override public void onRebind(Intent intent) { // A client is binding to the service with bindService(), // after onUnbind() has already been called Utils.logDebug(TAG, "onRebind"); if (mMission != null) { mMission.onRebind(); } } @Override public void onDestroy() { // The service is no longer used and is being destroyed. Utils.logDebug(TAG, "onDestroy"); mGoogleApiClientWrapper.disconnect(); if (mIsTextToSpeechReady) { mTextToSpeech.shutdown(); } if (mMediaPlayer != null) { mMediaPlayer.reset(); } mUpdateHandler.removeCallbacks(this); unregisterReceiver(mReceiver); if (mMission != null) { mMission.cleanup(); } } /** * Callback listener for MediaPlayer. * @param player MediaPlayer instance. */ @Override public void onCompletion(MediaPlayer player) { endPlayback(); } /** * A Binder for the connection between MainService and MainActivity that allows MainActivity * to get the running instance of MainService. */ public class MainBinder extends Binder { MainService getService() { return MainService.this; } } /** * Create a notification action that upon selection triggers the provided action. * @param intent Intent to carry out when the notification action is selected. * @param actionIconResourceId Resource Id of icon for this action. * @param actionDescription Name of this action. * @return A notification action that can be selected. */ public NotificationCompat.Action makeNotificationAction(Intent intent, int actionIconResourceId, String actionDescription) { PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); return new NotificationCompat.Action(actionIconResourceId, actionDescription, pendingIntent); } /** * Builds and posts a notification from a set of options. * @param options The options to build the notification. */ public void postActionNotification(NotificationOptions options) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setSmallIcon(options.getSmallIconResourceId()); builder.setContentTitle(options.getTitle()); builder.setContentText(options.getContent()); builder.setDefaults(options.getNotificationDefaults()); builder.setPriority(options.getNotificationPriority()); builder.setVibrate(options.getVibratePattern()); if (options.getActions() != null) { for (NotificationCompat.Action action : options.getActions()) { builder.addAction(action); } } NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(options.getNotificationId(), builder.build()); } public boolean isMissionRunning() { return mState == State.MISSION_RUNNING; } public boolean shouldDisplayEndScreen() { return mState == State.END_SCREEN; } public void reset() { setAndInitNextState(State.UNINITIALIZED); } public ArrayList getOverallFictionalProgress() { return mMission.getOverallFictionalProgress(); } /** * Gets fitness statistics for the last played game. * @return An array list of fitness statistics to display. */ public ArrayList getFitnessStatistics() { return getCurrentMission().getFitnessStatistics(); } public Mission getCurrentMission() { return this.mMission; } /** * Queue a sound into the audio queue. * @param uri The Uri of the sound. * @param listener The listener to the sound. This is usually MainService but can be overridden. */ public void queueSound(Uri uri, MediaPlayer.OnCompletionListener listener) { mAudioQueue.offer(new AudioQueueItem(uri, listener)); } /** * Removes the first instance of a sound from the audio queue. * @param uri Uri of the item to be removed. */ public void dequeueSound(Uri uri) { mAudioQueue.remove(new AudioQueueItem(uri, null)); } /** * Obtain audio focus for the application. This also checks if we are currently playing any * other audio clips, so it checks for "audio focus" within the app. * @return True if audio focus is obtained. False otherwise. */ public boolean obtainAudioFocus() { if (mMediaPlayer.isPlaying() || mTextToSpeech.isSpeaking()) { return false; } int result = mAudioManager.requestAudioFocus( mAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); return (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED); } /** * End audio playback, and abandon audio focus. */ public void endPlayback() { mMediaPlayer.reset(); mAudioManager.abandonAudioFocus(mAudioFocusChangeListener); } protected TextToSpeech getTextToSpeech() { return mIsTextToSpeechReady? mTextToSpeech : null; } /** * Checks if the state transition is valid. * @param state State to transition to. * @return True if the transition is valid, false if not. */ private boolean canEnterState(State state) { if (mState == state) { return false; } boolean canEnterState = true; switch (state) { case UNINITIALIZED: break; case MISSION_LOADED: if (mState == State.MISSION_RUNNING) { canEnterState = false; Utils.logDebug(TAG, "Can not enter MISSION_LOADED state from MISSION_RUNNING state."); } break; case MISSION_RUNNING: if (mState != State.MISSION_LOADED) { canEnterState = false; Utils.logDebug(TAG, "Can only enter MISSION_RUNNING state from MISSION_LOADED state."); } break; case END_SCREEN: if (mState != State.MISSION_RUNNING) { canEnterState = false; Utils.logDebug(TAG, "Can only enter END_SCREEN state from MISSION_RUNNING state."); } break; } return canEnterState; } /** * Sets the next state if possible. * @param state State to transition to. */ private void setAndInitNextState(State state) { if (!canEnterState(state)) { return; } mState = state; switch (mState) { case UNINITIALIZED: break; case MISSION_LOADED: mMission.prepare(mGoogleApiClientWrapper); mUpdateHandler.post(this); break; case MISSION_RUNNING: mMission.start(); broadcastStart(); break; case END_SCREEN: mUpdateHandler.removeCallbacks(this); mMission.cleanup(); broadcastEnd(); break; } } private void update() { if (mState == State.MISSION_LOADED && isReady()) { setAndInitNextState(State.MISSION_RUNNING); } if (mState == State.MISSION_RUNNING) { mMission.update(); if (mMission.isDone()) { endMission(); } } // Consume the audio queue if it's not empty and if we are able to obtain audio focus. if (!mAudioQueue.isEmpty() && obtainAudioFocus()) { playFirstInQueue(); } } /** * Play the first item in the audio queue. */ private void playFirstInQueue() { AudioQueueItem queueItem = mAudioQueue.poll(); try { mMediaPlayer.setDataSource(this, queueItem.mUri); } catch (IOException e) { e.printStackTrace(); // Data source does not exist. Skip playback. endPlayback(); return; } mMediaPlayer.setOnCompletionListener(queueItem.mListener); try { mMediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); // Error in reading the data source. Skip playback. endPlayback(); return; } mMediaPlayer.start(); } /** * @return True if asynchronous preparations are all done, so that a mission can be started. */ private boolean isReady() { return mIsTextToSpeechReady && mGoogleApiClientWrapper.isClientReady(); } /** * Broadcast to MainActivity to enable back navigation. */ private void enableBackNavigation() { sendBroadcast(new Intent(MainActivity.ENABLE_BACK)); } /** * Display a Toast that requests user to reselect their mission. */ private void requestReselection() { Toast.makeText(this, "Mission load failure. Select again.", Toast.LENGTH_SHORT).show(); enableBackNavigation(); } /** * Broadcast to MainActivity that mission has started. */ private void broadcastStart() { sendBroadcast(new Intent(MainActivity.MISSION_START)); } /** * Broadcast to MainActivity that mission has ended. */ private void broadcastEnd() { sendBroadcast(new Intent(MainActivity.MISSION_END)); } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/Mission.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v4.app.NotificationCompat; import com.google.android.gms.fitness.data.DataPoint; import com.google.android.gms.fitness.data.DataType; import com.google.android.gms.fitness.data.Field; import com.google.android.gms.fitness.data.Value; import com.google.android.gms.fitness.request.OnDataPointListener; import com.google.android.gms.fitness.request.SensorRequest; import com.google.fpl.gim.examplegame.gui.NotificationOptions; import com.google.fpl.gim.examplegame.google.FitDataTypeSetting; import com.google.fpl.gim.examplegame.google.GoogleApiClientWrapper; import com.google.fpl.gim.examplegame.utils.MissionParseException; import com.google.fpl.gim.examplegame.utils.MissionParser; import com.google.fpl.gim.examplegame.utils.Utils; import java.io.InputStream; import java.util.ArrayList; /** * A mission is a complete gameplay during which the exercising user will be challenged to defeat * fictional pursuers. The user will have a weapon that can only be charged by running faster. */ public class Mission implements OnDataPointListener { private static final String TAG = Mission.class.getSimpleName(); private static final FitDataTypeSetting[] TRACKED_DATA_TYPES = { new FitDataTypeSetting( true /* isRequired */, DataType.TYPE_STEP_COUNT_DELTA, 1 /* samplingRateSeconds */, SensorRequest.ACCURACY_MODE_DEFAULT), new FitDataTypeSetting( false /* isRequired */, DataType.TYPE_SPEED, 1 /* samplingRateSeconds */, SensorRequest.ACCURACY_MODE_HIGH), }; private static final String UPDATE_FITNESS_STATS = "com.google.fpl.gim.examplegame.UPDATE_FITNESS_STATS"; // ID that signifies the moment whose next is this is an ending moment. private static final String DEFAULT_END_ID = null; private MissionData mData; // Access to MainService to obtain and use Android Context. private MainService mService; private boolean mIsDone = false; private boolean mIsStarted = false; // Access to GoogleFitApiClient for fit data private GoogleApiClientWrapper mGoogleApiClientWrapper; // Fitness stats for the mission as a whole. private int mTotalNumStepsTaken = 0; private int mTotalNumIntervalsCompleted = 0; private long mMissionStartTimeNanos; // Fitness stats for a small portion of the mission. private int mNumStepsSinceBeginningOfSample = 0; private long mSampleStartTimeNanos; private float mCurrentAverageMinutesPerMile = 0f; private static final float AVERAGE_SPEED_SAMPLE_RATE_SECONDS = 10.0f; private static final float LENGTH_OF_RUNNING_STRIDE_FEET = 5.5f; private static final float MAXIMUM_MINUTES_PER_MILE = 1000f; private boolean mIsAtChallengePace = false; private long mTimestampStartOfChallengePaceNanos; private static final String AT_CHALLENGE_PACE_RESOURCE = "android.resource://com.google.fpl.gim.examplegame/raw/atchallengepace"; private static final String NO_LONGER_AT_CHALLENGE_PACE_RESOURCE = "android.resource://com.google.fpl.gim.examplegame/raw/nolongeratchallengepace"; private static final String WEAPON_CHARGED_RESOURCE = "android.resource://com.google.fpl.gim.examplegame/raw/weaponcharged"; private final Uri AT_CHALLENGE_PACE_URI = Uri.parse(AT_CHALLENGE_PACE_RESOURCE); private final Uri NO_LONGER_AT_CHALLENGE_PACE_URI = Uri.parse(NO_LONGER_AT_CHALLENGE_PACE_RESOURCE); private final Uri WEAPON_CHARGED_URI = Uri.parse(WEAPON_CHARGED_RESOURCE); // The current time represented in nanoseconds. private long mNowNanos; private boolean mIsWeaponCharged = false; private float mLastWeaponCharge; private int mNumEnemiesDefeated = 0; private ArrayList mOverallFictionalProgress = new ArrayList<>(); public Mission(MissionData data) { this.mData = data; } /** * Makes the moment referred to by nextMomentId the current Moment. Checks if the game should * end by checking the nextMomentId. * @param nextMomentId The ID of the moment to make the current moment. */ public void changeCurrentMoment(String nextMomentId, long now) { if (nextMomentId == DEFAULT_END_ID || nextMomentId.equals(DEFAULT_END_ID)) { mIsDone = true; return; } mData.setCurrentMomentId(nextMomentId); mData.getCurrentMoment().start(now); } /** * Loads the moments read from an xml file that define a mission into the mission data. * @param missionStream An input stream for an xml file. * @throws com.google.fpl.gim.examplegame.utils.MissionParseException Thrown when file parsing failed due to parser configuration, * input exceptions, or incorrectly structured file. */ public void readMoments(InputStream missionStream) throws MissionParseException { // Exceptions may be thrown from MissionParser.parseMission MissionParser.parseMission(missionStream, this); } public void start() { mNowNanos = System.nanoTime(); mMissionStartTimeNanos = mNowNanos; changeCurrentMoment(mData.getFirstMomentId(), mNowNanos); mIsStarted = true; mSampleStartTimeNanos = mNowNanos; mLastWeaponCharge = 0f; // Create the notification to notify the user of their current fitness statistics. postFitnessNotification(getFitnessNotificationTitle()); } public void cleanup() { Utils.logDebug(TAG, mOverallFictionalProgress.toString()); // Clean up the current moment. if (mData.getCurrentMoment() != null) { mData.getCurrentMoment().end(); } NotificationManager notificationManager = (NotificationManager) getService() .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(MainService.CHOICE_NOTIFICATION_ID); notificationManager.cancel(MainService.FITNESS_STATS_NOTIFICATION_ID); if (mGoogleApiClientWrapper != null) { mGoogleApiClientWrapper.endFitDataSession(TRACKED_DATA_TYPES, this); mGoogleApiClientWrapper = null; } } public void addMoment(String id, Moment moment) { this.mData.addMoment(id, moment); } public void setFirstMomentId(String firstMomentId) { this.mData.setFirstMomentId(firstMomentId); } public void update() { mNowNanos = System.nanoTime(); // Calculate average speed at a consistent time interval. float timePassedSeconds = Utils.nanosToSeconds(mNowNanos - mSampleStartTimeNanos); if (timePassedSeconds >= AVERAGE_SPEED_SAMPLE_RATE_SECONDS) { calculateAverageMinutesPerMile(); } Moment currentMoment = mData.getCurrentMoment(); currentMoment.update(mNowNanos); if (currentMoment.isDone()) { mOverallFictionalProgress.addAll(currentMoment.getFictionalProgress()); currentMoment.end(); changeCurrentMoment(currentMoment.getNextMomentId(), mNowNanos); } if (mLastWeaponCharge != getWeaponChargedPercentage()) { mLastWeaponCharge = getWeaponChargedPercentage(); // Create the notification to notify the user of their current fitness statistics. postFitnessNotification(getFitnessNotificationTitle()); } Intent updateFitnessStatsIntent = new Intent(); updateFitnessStatsIntent.setAction(UPDATE_FITNESS_STATS); getService().sendBroadcast(updateFitnessStatsIntent); } public void postFitnessNotification(String title) { NotificationOptions notificationOptions = NotificationOptions.getDefaultNotificationOptions(); notificationOptions.setTitle(title); notificationOptions.setContent(getService() .getString(R.string.weapon_status_notification_text)); notificationOptions.setNotificationId(MainService.FITNESS_STATS_NOTIFICATION_ID); notificationOptions.setPriorityAsHigh(); notificationOptions.setNotificationDefaults(NotificationCompat.DEFAULT_LIGHTS); getService().postActionNotification(notificationOptions); } public void setService(MainService service) { this.mService = service; } public MainService getService() { return this.mService; } public boolean isDone() { return mIsDone; } public void prepare(GoogleApiClientWrapper googleApiClientWrapper) { Utils.logDebug(TAG, "Mission prepared."); // Start collecting Google Fit data mGoogleApiClientWrapper = googleApiClientWrapper; mGoogleApiClientWrapper.startFitDataSession( TRACKED_DATA_TYPES, getMissionData().getMissionName(), this); } public boolean isWeaponCharged() { return mIsWeaponCharged; } public MissionData getMissionData() { return this.mData; } /** * Restarts the current moment with a time delay. */ public void restartMoment() { if (mData.getCurrentMoment() != null) { mData.getCurrentMoment().restartWithDelay(mNowNanos, 0f); } } public void applyOutcome(Outcome outcome) { if (outcome.numEnemiesDefeatedIncremented()) { mNumEnemiesDefeated++; } if (outcome.weaponChargeDepleted()) { mIsWeaponCharged = false; } } public ArrayList getOverallFictionalProgress() { return mOverallFictionalProgress; } @Override public void onDataPoint(DataPoint dataPoint) { // If we get data before the mission has started, discard them. if (!mIsStarted) { return; } DataType dataType = dataPoint.getDataType(); for (Field field : dataType.getFields()) { Value val = dataPoint.getValue(field); if (dataType.equals(DataType.TYPE_STEP_COUNT_DELTA)) { onStepTaken(val.asInt()); } else if (dataType.equals(DataType.TYPE_SPEED)) { // Data comes in as meters per second, have to convert to minutes per mile. float speedMetersPerSeconds = val.asFloat(); updateChallengePace(Utils.metersPerSecondToMinutesPerMile(speedMetersPerSeconds)); } } } public void onStepTaken(int steps) { mNumStepsSinceBeginningOfSample += steps; mTotalNumStepsTaken += steps; Utils.logDebug(TAG, "Fit data update. You have now taken " + mTotalNumStepsTaken + " steps."); // Update UI whenever a step is taken Intent updateFitnessStatsIntent = new Intent(); updateFitnessStatsIntent.setAction(UPDATE_FITNESS_STATS); getService().sendBroadcast(updateFitnessStatsIntent); } public int getNumSteps() { return this.mTotalNumStepsTaken; } public float getMinutesPerMile() { return this.mCurrentAverageMinutesPerMile; } public int getNumMinutesExercised() { long timePassedNanos = mNowNanos - mMissionStartTimeNanos; int timePassedSeconds = (int) Utils.nanosToSeconds(timePassedNanos); int timePassedMinutes = timePassedSeconds / Utils.MINUTES_TO_SECONDS_SCALE; return timePassedMinutes; } public int getNumSecondsExercised() { long timePassedNanos = mNowNanos - mMissionStartTimeNanos; int timePassedSeconds = (int) Utils.nanosToSeconds(timePassedNanos); return timePassedSeconds % Utils.MINUTES_TO_SECONDS_SCALE; } public int getWeaponChargedPercentage() { if (mIsWeaponCharged) { return 100; } if (!mIsAtChallengePace) { return 0; } long timeAtChallengePaceNanos = mNowNanos - mTimestampStartOfChallengePaceNanos; float timeAtChallengePaceMinutes = Utils.nanosToMinutes(timeAtChallengePaceNanos); float weaponChargedPercentage = timeAtChallengePaceMinutes / mData.getLengthOfIntervalMinutes() * 100; return (int) weaponChargedPercentage; } public float getChallengePace() { return mData.getChallengePaceMinutesPerMile(); } public void onRebind() { // Update UI after app wakes up (after the Activity is rebound to the Service) Intent updateFitnessStatsIntent = new Intent(); updateFitnessStatsIntent.setAction(UPDATE_FITNESS_STATS); getService().sendBroadcast(updateFitnessStatsIntent); } public static float getMaximumMinutesPerMile() { return MAXIMUM_MINUTES_PER_MILE; } public ArrayList getFitnessStatistics() { ArrayList fitnessStats = new ArrayList<>(); String numStepsTaken = String.format(getService() .getString(R.string.fitness_stat_num_steps), mTotalNumStepsTaken); fitnessStats.add(numStepsTaken); String numIntervalsCompleted = String.format(getService() .getString(R.string.fitness_stat_num_intervals), mTotalNumIntervalsCompleted); fitnessStats.add(numIntervalsCompleted); return fitnessStats; } private void calculateAverageMinutesPerMile() { float timePassedSeconds = Utils.nanosToSeconds(mNowNanos - mSampleStartTimeNanos); float timePassedMinutes = Utils.secondsToMinutes(timePassedSeconds); float distanceTraveledFeet = mNumStepsSinceBeginningOfSample * LENGTH_OF_RUNNING_STRIDE_FEET; float distanceTraveledMiles = Utils.feetToMiles(distanceTraveledFeet); if (distanceTraveledMiles > 0) { updateChallengePace(timePassedMinutes / distanceTraveledMiles); } else { updateChallengePace(0.0f); } } private void updateChallengePace(float averageMinutesPerMile) { String updateText; if (averageMinutesPerMile > 0) { mCurrentAverageMinutesPerMile = averageMinutesPerMile; updateText = (int)(mCurrentAverageMinutesPerMile) + getService().getString(R.string.log_message_minutes_per_mile); } else { mCurrentAverageMinutesPerMile = MAXIMUM_MINUTES_PER_MILE; updateText = getService().getString(R.string.log_message_you_are_not_moving); } Utils.logDebug(TAG, updateText); evaluateChallengePace(); // Reset start time and number of steps for next average speed sample. mSampleStartTimeNanos = mNowNanos; mNumStepsSinceBeginningOfSample = 0; } private void evaluateChallengePace() { // Player is currently at challenge pace. if (mCurrentAverageMinutesPerMile <= mData.getChallengePaceMinutesPerMile()) { // At last check, player was not at challenge pace. if (!mIsAtChallengePace) { mService.queueSound(AT_CHALLENGE_PACE_URI, mService); mTimestampStartOfChallengePaceNanos = mNowNanos; } // Player has been running at challenge pace for enough time to charge their weapon. else if (!mIsWeaponCharged && Utils.nanosToMinutes(mNowNanos - mTimestampStartOfChallengePaceNanos) >= mData.getLengthOfIntervalMinutes()) { mService.queueSound(WEAPON_CHARGED_URI, mService); mIsWeaponCharged = true; mTotalNumIntervalsCompleted++; } mIsAtChallengePace = true; } // Player is not currently at challenge pace. else { // At last check, player was at challenge pace. if (mIsAtChallengePace) { mService.queueSound(NO_LONGER_AT_CHALLENGE_PACE_URI, mService); } mIsAtChallengePace = false; } } private String getFitnessNotificationTitle() { return getWeaponChargedPercentage() + getService().getString(R.string.weapon_status_notification_title); } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/MissionData.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import java.util.HashMap; /** * Encapsulates all of the game data that is necessary to represent a mission. */ public class MissionData { private String mMissionName; // User-facing name of mission. // ID must be unique to each mission private String mMissionId; private float mLengthOfMissionMinutes; private float mLengthOfIntervalMinutes; private float mChallengePaceMinutesPerMile; private HashMap mAllMoments; private String mFirstMomentId; private String mCurrentMomentId; /** * Most general constructor. Used when wanting to construct most pieces of MissionData * explicitly. * @param missionId String identifying the Mission. * @param lengthOfGameMinutes Total length of game. * @param lengthOfIntervalMinutes Length of a running interval. * @param allMoments HashMap containing all Moments that define this Mission. * @param firstMomentId The first Moment to be executed during the Mission. * @param currentMomentId The current Moment of the Mission. */ public MissionData(String missionName, String missionId, float lengthOfGameMinutes, float lengthOfIntervalMinutes, float challengePaceMinutesPerMile, HashMap allMoments, String firstMomentId, String currentMomentId) { this.mMissionName = missionName; this.mMissionId = missionId; this.mLengthOfMissionMinutes = lengthOfGameMinutes; this.mLengthOfIntervalMinutes = lengthOfIntervalMinutes; this.mChallengePaceMinutesPerMile = challengePaceMinutesPerMile; this.mAllMoments = allMoments; this.mFirstMomentId = firstMomentId; this.mCurrentMomentId = currentMomentId; } /** * Constructor used when populating MissionData with information from menu screens. * @param missionId String identifying the Mission. * @param lengthOfGameMinutes Total length of game. * @param lengthOfIntervalMinutes Length of a running interval. */ public MissionData(String missionName, String missionId, float lengthOfGameMinutes, float lengthOfIntervalMinutes, float challengePaceMinutesPerMile) { this(missionName, missionId, lengthOfGameMinutes, lengthOfIntervalMinutes, challengePaceMinutesPerMile, new HashMap(), null, null); } public String getMissionName() { return this.mMissionName; } public String getMissionId() { return this.mMissionId; } public float getLengthOfMissionMinutes() { return this.mLengthOfMissionMinutes; } public float getLengthOfIntervalMinutes() { return this.mLengthOfIntervalMinutes; } public float getChallengePaceMinutesPerMile() { return this.mChallengePaceMinutesPerMile; } public Moment getMomentFromId(String momentId) { return mAllMoments.get(momentId); } public String getCurrentMomentId() { return this.mCurrentMomentId; } public String getFirstMomentId() { return this.mFirstMomentId; } public void setCurrentMomentId(String currentMomentId) { this.mCurrentMomentId = currentMomentId; } public void addMoment(String momentId, Moment moment) { this.mAllMoments.put(momentId, moment); } public void setFirstMomentId(String firstMomentId) { this.mFirstMomentId = firstMomentId; } public Moment getCurrentMoment() { return mAllMoments.get(mCurrentMomentId); } public int getNumMoments() { return mAllMoments.size(); } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/Moment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import com.google.fpl.gim.examplegame.utils.Utils; import java.util.ArrayList; /** * A Moment is a discrete event within a Mission. Moments know when they are finished ('isDone()'), * and they are never reused. */ public abstract class Moment { // The mission to which this moment belongs. private Mission mMission; public boolean mIsDone; private boolean mShouldRestart; private long mTimeWhenRestartRequestedNanos; private long mRestartDelayLengthNanos; /** * @param mission The Mission to which this moment belongs. Cannot be changed after * instantiation - each Moment is irrevocably associated with a Mission. */ protected Moment(Mission mission) { this.mMission = mission; } public Mission getMission() { return mMission; } /** * Called on the current moment to determine if it is appropriate to move on. * @return true if this moment no longer should be active as the current moment. */ public boolean isDone() { return mIsDone; } public void setIsDone(boolean isDone) { this.mIsDone = isDone; } /** * Update the moment information for the current time. Default behavior checks if the Moment * should restart, and does. * @param nowNanos The current time, represented in nanoseconds. */ public void update(long nowNanos) { if (mShouldRestart && nowNanos > mTimeWhenRestartRequestedNanos + mRestartDelayLengthNanos) { restart(nowNanos); } } /** * Read the id of the next Moment associated with this Moment. * @return String identifying the next Moment associated with this Moment. */ public abstract String getNextMomentId(); /** * Make this moment active. Runs when the moment begins. * @param nowNanos The current time, represented in nanoseconds. */ public void start(long nowNanos) { this.mIsDone = false; this.mShouldRestart = false; } /** * Ends the current moment. */ public abstract void end(); /** * Restarts a moment. */ public abstract void restart(long nowNanos); public void restartWithDelay(long nowNanos, float secondsDelayRestart) { mShouldRestart = true; mTimeWhenRestartRequestedNanos = nowNanos; mRestartDelayLengthNanos = Utils.secondsToNanos(secondsDelayRestart); } public abstract ArrayList getFictionalProgress(); } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/MomentData.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import java.util.ArrayList; /** * Encapsulates the data that is needed to define a unique Moment. */ public abstract class MomentData { // The id of this moment. Must be unique across the moments in the mission. private final String mMomentId; // The moment to go to next. private final String mNextMomentId; private ArrayList mFictionalProgress; /** * Constructor to explicitly set all fields for a ChoiceMomentData. * @param momentId Identifier for the ChoiceMoment. * @param nextMomentId The moment following this one. Null if is the last moment in a mission. * @param fictionalProgress Fictional progress for this moment. */ public MomentData(String momentId, String nextMomentId, ArrayList fictionalProgress) { mMomentId = momentId; mNextMomentId = nextMomentId; mFictionalProgress = fictionalProgress; } public String getMomentId() { return mMomentId; } public String getNextMomentId() { return mNextMomentId; } public ArrayList getFictionalProgress() { return mFictionalProgress; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/Outcome.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; /** * Encapsulates the game data changes that should occur as a result of a certain Choice */ public class Outcome { private boolean mDepleteWeaponCharge; private boolean mIncrementNumEnemiesDefeated; public Outcome(boolean depleteWeaponCharge, boolean incrementNumEnemiesDefeated) { this.mDepleteWeaponCharge = depleteWeaponCharge; this.mIncrementNumEnemiesDefeated = incrementNumEnemiesDefeated; } public boolean weaponChargeDepleted() { return this.mDepleteWeaponCharge; } public boolean numEnemiesDefeatedIncremented() { return this.mIncrementNumEnemiesDefeated; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/SfxMoment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import android.media.MediaPlayer; import java.io.IOException; import java.util.ArrayList; /** * Describes a Moment in which the user listens to a pre-recorded sound effect as part of the * gameplay. */ public class SfxMoment extends Moment implements MediaPlayer.OnCompletionListener { private SfxMomentData mData; public SfxMoment(Mission mission, SfxMomentData data) { super(mission); this.mData = data; } @Override public void start(long nowNanos) { super.start(nowNanos); getMission().getService().queueSound(mData.getUriAsset(), this); } @Override public void end() { } @Override public String getNextMomentId() { return mData.getNextMomentId(); } /** * We need to know when our specific sfx is done playing. Then we fallback to the default * onCompletionListener to finish cleaning up. */ @Override public void onCompletion(MediaPlayer mp) { setIsDone(true); getMission().getService().onCompletion(mp); } @Override public void restart(long nowNanos) { getMission().getService().dequeueSound(mData.getUriAsset()); // Try to start again. start(nowNanos); } public SfxMomentData getMomentData() { return this.mData; } @Override public ArrayList getFictionalProgress() { return mData.getFictionalProgress(); } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/SfxMomentData.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import android.net.Uri; import java.util.ArrayList; /** * Encapsulates the data that is needed to define a unique NotificationAudioMoment. */ public class SfxMomentData extends MomentData { // The name of the sound file to play private final Uri mUriAsset; /** * Constructor to explicitly set all fields for a ChoiceMomentData. * @param momentId Identifier for the ChoiceMoment. * @param nextMomentId The moment following this one. Null if is the last moment in a mission. * @param fictionalProgress Fictional progress for this moment. * @param uriAsset Uri of the sound to play with this moment. */ public SfxMomentData(String momentId, String nextMomentId, ArrayList fictionalProgress, Uri uriAsset) { super(momentId, nextMomentId, fictionalProgress); mUriAsset = uriAsset; } public Uri getUriAsset() { return mUriAsset; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/SpokenTextMoment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import android.speech.tts.TextToSpeech; import android.speech.tts.UtteranceProgressListener; import com.google.fpl.gim.examplegame.utils.Utils; import java.util.ArrayList; import java.util.HashMap; /** * Describes a Moment in which the user listens to a piece of fiction as part of the gameplay. * The fiction will be read aloud using Android's text-to-speech capabilities. */ public class SpokenTextMoment extends Moment { private static final String TAG = SpokenTextMoment.class.getSimpleName(); private SpokenTextMomentData mData; private static final float RETRY_WAIT_TIME_SECONDS = 2.5f; // Buffer time before speaking with TextToSpeech. private static final long SILENCE_LENGTH_MILLIS = 500; // Determines behavior to execute during TextToSpeech speaking. private UtteranceProgressListener mUtteranceProgressListener = new UtteranceProgressListener() { @Override public void onStart(String utteranceId) { } @Override /** * Determines behavior when TextToSpeech has completed speaking, or stopped. */ public void onDone(String utteranceId) { setIsDone(true); getMission().getService().endPlayback(); } @Override public void onError(String utteranceId) { } }; public SpokenTextMoment(Mission mission, SpokenTextMomentData data) { super(mission); this.mData = data; } @Override public void start(long nowNanos) { super.start(nowNanos); Utils.logDebug(TAG, "SpokenTextMoment \"" + mData.getMomentId() + "\" started."); if (getMission().getService().obtainAudioFocus()) { speak(); } else { // Try again at a future time. restartWithDelay(nowNanos, RETRY_WAIT_TIME_SECONDS); } } @Override public void end() { Utils.logDebug(TAG, "SpokenTextMoment \"" + mData.getMomentId() + "\" ended."); getMission().getService().getTextToSpeech().setOnUtteranceProgressListener(null); getMission().getService().getTextToSpeech().stop(); } public String getNextMomentId() { return mData.getNextMomentId(); } /** * Use TextToSpeech to say the words associated with this Moment. */ private void speak() { TextToSpeech textToSpeech = getMission().getService().getTextToSpeech(); textToSpeech.setOnUtteranceProgressListener(mUtteranceProgressListener); textToSpeech.playSilence(SILENCE_LENGTH_MILLIS, TextToSpeech.QUEUE_ADD, null); HashMap map = new HashMap<>(); map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, mData.getMomentId()); textToSpeech.speak(mData.getTextToSpeak(), TextToSpeech.QUEUE_ADD, map); } @Override public void restart(long nowNanos) { // Stop anything in progress. end(); start(nowNanos); } public SpokenTextMomentData getMomentData() { return this.mData; } @Override public ArrayList getFictionalProgress() { return mData.getFictionalProgress(); } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/SpokenTextMomentData.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import java.util.ArrayList; /** * Encapsulates the data that is needed to define a unique FictionAudioMoment. */ public class SpokenTextMomentData extends MomentData { // The text to be read aloud using text-to-speech private final String mTextToSpeak; /** * Constructor to explicitly set all fields for a ChoiceMomentData. * @param momentId Identifier for the ChoiceMoment. * @param nextMomentId The moment following this one. Null if is the last moment in a mission. * @param fictionalProgress Fictional progress for this moment. * @param textToSpeak Words associated with this moment. */ public SpokenTextMomentData(String momentId, String nextMomentId, ArrayList fictionalProgress, String textToSpeak) { super(momentId, nextMomentId, fictionalProgress); mTextToSpeak = textToSpeak; } public String getTextToSpeak() { return mTextToSpeak; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/TimerMoment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import com.google.fpl.gim.examplegame.utils.Utils; import java.util.ArrayList; /** * Describes a Moment in which there is a gap in gameplay for a given amount of time. */ public class TimerMoment extends Moment { private static final String TAG = TimerMoment.class.getSimpleName(); private TimerMomentData mData; private long mStartTimeNanos; public TimerMoment(Mission mission, TimerMomentData data) { super(mission); this.mData = data; } @Override public void update(long nowNanos) { setIsDone(hasMomentTimeElapsed(nowNanos)); } @Override public void start(long nowNanos) { super.start(nowNanos); Utils.logDebug(TAG, "TimerMoment \"" + mData.getMomentId() + "\" started."); setStartTimeNanos(nowNanos); } @Override public void end() { Utils.logDebug(TAG, "TimerMoment \"" + mData.getMomentId() + "\" ended."); } /** * Determines if the TimerMoment has elapsed. * @param nowNanos The current time. * @return True if the time since the TimerMoment started is greater than or equal to the length * of the timer moment. */ public boolean hasMomentTimeElapsed(long nowNanos) { return (nowNanos - mStartTimeNanos) >= Utils.minutesToNanos(mData.getLengthMinutes()); } public void setStartTimeNanos(long startTimeNanos) { this.mStartTimeNanos = startTimeNanos; } @Override public String getNextMomentId() { return mData.getNextMomentId(); } @Override public void restart(long nowNanos) { // No additional tear down or resetting necessary. start(nowNanos); } public TimerMomentData getMomentData() { return this.mData; } @Override public ArrayList getFictionalProgress() { return mData.getFictionalProgress(); } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/TimerMomentData.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame; import java.util.ArrayList; /** * Encapsulates the data that is needed to define a unique TimerMoment. */ public class TimerMomentData extends MomentData { // The length of the timer in minutes private float mLengthMinutes; /** * Constructor to explicitly set all fields for a ChoiceMomentData. * @param momentId Identifier for the ChoiceMoment. * @param nextMomentId The moment following this one. Null if is the last moment in a mission. * @param fictionalProgress Fictional progress for this moment. * @param lengthMinutes Length of this moment. */ public TimerMomentData(String momentId, String nextMomentId, ArrayList fictionalProgress, float lengthMinutes) { super(momentId, nextMomentId, fictionalProgress); mLengthMinutes = lengthMinutes; } public float getLengthMinutes() { return mLengthMinutes; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/google/FitDataTypeSetting.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.google; import com.google.android.gms.fitness.data.DataType; /** * This keeps track of the sensor data types and their registration settings. */ public class FitDataTypeSetting { private boolean mRequired; // Is this data type required for the game to start? private DataType mDataType; private long mSamplingRateSeconds; private int mAccuracyMode; public FitDataTypeSetting( boolean required, DataType dataType, long samplingRateSeconds, int accuracyMode) { mRequired = required; mDataType = dataType; mSamplingRateSeconds = samplingRateSeconds; mAccuracyMode = accuracyMode; } public boolean isRequired() { return mRequired; } public DataType getDataType() { return mDataType; } public long getSamplingRateSeconds() { return mSamplingRateSeconds; } public int getAccuracyMode() { return mAccuracyMode; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/google/FitResultCallback.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.google; import android.util.Log; import com.google.android.gms.common.api.Result; import com.google.android.gms.common.api.Status; import com.google.android.gms.fitness.FitnessStatusCodes; import com.google.android.gms.fitness.data.DataType; import com.google.fpl.gim.examplegame.utils.Utils; /** * Implements ResultCallback while allowing to record more state so we can change game flow * accordingly. */ public class FitResultCallback implements com.google.android.gms.common.api.ResultCallback { private static final String TAG = "GoogleFitResultCallback"; // Enum type for keeping track of which API generated this callback. public enum RegisterType { SENSORS, RECORDING, SESSION, } GoogleApiClientWrapper mGoogleApiClient; RegisterType mRegisterType; DataType mDataType; boolean mSubscribe; // True if subscribe, false if unsubscribe. /** * Default constructor. * @param googleApiClient The GoogleApiClientWrapper to pass data back to. * @param registerType The type of call that resulted in this callback. * @param dataType The data type we are trying to process. * @param subscribe If true, this is a subscribe or a register call. */ public FitResultCallback( GoogleApiClientWrapper googleApiClient, RegisterType registerType, DataType dataType, boolean subscribe) { mGoogleApiClient = googleApiClient; mRegisterType = registerType; mDataType = dataType; mSubscribe = subscribe; } @Override public void onResult(R result) { switch (mRegisterType) { case SENSORS: onSensorResult(result.getStatus()); break; case RECORDING: onRecordingResult(result.getStatus()); break; case SESSION: onSessionResult(result.getStatus()); break; default: Log.e(TAG, "Unknown enum type."); } } private void onSensorResult(Status status) { if (status.isSuccess()) { // There is a lapse between this callback to actually getting data from the listener, // depending on the data type. It is a known issue, by design. You can account for that // delay with display text or other mechanisms. mGoogleApiClient.sensorRegistered(mDataType); Utils.logDebug(TAG, "Successfully registered sensor for " + mDataType.toString()); } else { Utils.logDebug(TAG, "There was a problem registering ." + mDataType + "\n" + status.getStatusMessage()); } } private void onRecordingResult(Status status) { if (mSubscribe) { onRecordingSubscription(status); } else { onRecordingUnsubscription(status); } } private void onRecordingSubscription(Status status) { if (status.isSuccess()) { if (status.getStatusCode() == FitnessStatusCodes.SUCCESS_ALREADY_SUBSCRIBED) { Utils.logDebug(TAG, "Existing subscription for activity detected."); } else { Utils.logDebug(TAG, "Started recording data for " + mDataType); } } else { // For a better user experience, you can add visual error text indicating the session // will not be recorded to the cloud. Utils.logDebug(TAG, "Unable to start recording data for " + mDataType); } } private void onRecordingUnsubscription(Status status) { if (status.isSuccess()) { Utils.logDebug(TAG, "Stopped recording data for " + mDataType); } else { Utils.logDebug(TAG, "Unable to stop recording data for " + mDataType); } } private void onSessionResult(Status status) { if (mSubscribe) { onSessionSubscription(status); } else { onSessionUnsubscription(status); } } private void onSessionSubscription(Status status) { if (status.isSuccess()) { Utils.logDebug(TAG, "Started data session."); } else { // For a better user experience, you can add visual error text indicating the session // will not be identified in the cloud. Utils.logDebug(TAG, "Unable to start data session."); } } private void onSessionUnsubscription(Status status) { if (status.isSuccess()) { Utils.logDebug(TAG, "Ended data session."); } else { Utils.logDebug(TAG, "Unable to end data session."); } } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/google/GoogleApiClientWrapper.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.google; import android.app.Activity; import android.content.IntentSender; import android.os.Bundle; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.Status; import com.google.android.gms.fitness.Fitness; import com.google.android.gms.fitness.FitnessActivities; import com.google.android.gms.fitness.FitnessStatusCodes; import com.google.android.gms.fitness.data.DataType; import com.google.android.gms.fitness.data.Session; import com.google.android.gms.fitness.request.OnDataPointListener; import com.google.android.gms.fitness.request.SensorRequest; import com.google.android.gms.fitness.result.SessionStopResult; import com.google.android.gms.games.Games; import com.google.fpl.gim.examplegame.MainActivity; import com.google.fpl.gim.examplegame.utils.Utils; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Container class to hold a static instance of GoogleApiClient. This allows the MainActivity * class to implement the GoogleApiClient.OnConnectionFailedListener interface (which * requires an Activity to request authentications from the user) and the MainService class to * implement the GoogleApiClient.ConnectionCallbacks interface. This also allows the Google * API client to be subsequently accessed by either class. */ public class GoogleApiClientWrapper implements ConnectionCallbacks, OnConnectionFailedListener { private static final String TAG = GoogleApiClientWrapper.class.getSimpleName(); private static final String SESSION_NAME = "Games-in-Motion Mission"; public static final int REQUEST_CODE_OAUTH = 1; private boolean mAuthInProgress = false; private Activity mActivity; // Activity for GoogleApiClient to launch visual elements on. private GoogleApiClient mGoogleApiClient; private Set sensorsAwaitingRegistration = new HashSet<>(); /** * Builds a GoogleApiClient that connects to the Fitness Api. * @param activity The activity through which authorization UI will be launched. */ public void buildGoogleApiClient(Activity activity) { if (mGoogleApiClient != null) { return; } Utils.logDebug(TAG, "Building the Google Api Client."); mActivity = activity; // Create the Google API Client. mGoogleApiClient = new GoogleApiClient.Builder(activity, this, this) .addApi(Fitness.API) // Fitness API .addScope(Fitness.SCOPE_ACTIVITY_READ) // Fitness Scopes .addScope(Fitness.SCOPE_LOCATION_READ) .addApi(Games.API) // Games API .addScope(Games.SCOPE_GAMES) // Games Scope .build(); } public void connect() { // Make sure the app is not already connected or attempting to connect if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) { mGoogleApiClient.connect(); } } public void disconnect() { if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } @Override public void onConnected(Bundle connectionHint) { Utils.logDebug(TAG, "Connected!"); // Send the hint to Activity for UI updates ((MainActivity) mActivity).onFitStatusUpdated(true); } @Override public void onConnectionSuspended(int i) { // If your connection gets lost at some point, // you'll be able to determine the reason and react to it here. if (i == ConnectionCallbacks.CAUSE_NETWORK_LOST) { Utils.logDebug(TAG, "Connection lost. Cause: Network Lost."); } else if (i == ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) { Utils.logDebug(TAG, "Connection lost. Reason: Service Disconnected"); } // Send the hint to Activity for UI updates ((MainActivity) mActivity).onFitStatusUpdated(false); // Attempt to reconnect connect(); } @Override public void onConnectionFailed(ConnectionResult result) { Log.e(TAG, "Connection failed. Cause: " + result.toString()); if (!result.hasResolution()) { // Show the localized error dialog GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), mActivity, 0).show(); return; } // The failure has a resolution. Resolve it. // Called typically when the app is not yet authorized, and an // authorization dialog is displayed to the user. if (!mAuthInProgress && (result.getErrorCode() == ConnectionResult.SIGN_IN_REQUIRED || result.getErrorCode() == FitnessStatusCodes.NEEDS_OAUTH_PERMISSIONS)) { try { Utils.logDebug(TAG, "Attempting to resolve failed connection"); mAuthInProgress = true; result.startResolutionForResult(mActivity, REQUEST_CODE_OAUTH); } catch (IntentSender.SendIntentException e) { mAuthInProgress = false; Log.e(TAG, "Exception while starting resolution activity", e); } } } /** * Starts a new session for Fit data. This will take care of registering all the sensors, * recording the sensor data, and registering the data set as a session to Google Fit. * @param dataTypeSettings Types of data to listen to, in an array. * @param sessionDescription The description of the session. * @param listener The OnDataPointListener to receive sensor events. */ public void startFitDataSession(FitDataTypeSetting[] dataTypeSettings, String sessionDescription, OnDataPointListener listener) { for (FitDataTypeSetting dataTypeSetting : dataTypeSettings) { registerFitDataListener(dataTypeSetting, listener); startRecordingFitData(dataTypeSetting); } Session session = new Session.Builder() .setName(SESSION_NAME) .setDescription(sessionDescription) .setActivity(FitnessActivities.RUNNING_JOGGING) .setStartTime(System.currentTimeMillis(), TimeUnit.MILLISECONDS) .build(); PendingResult pendingResult = Fitness.SessionsApi.startSession(mGoogleApiClient, session); pendingResult.setResultCallback(new FitResultCallback( this, FitResultCallback.RegisterType.SESSION, null /* dataType */, true /* subscribe */)); } /** * Ends the session for Fit data. This will take care of un-registering all the sensors, * stop recording the sensor data, and stop recording the data set as a session to Google Fit. * @param dataTypeSettings Types of data to listen to, in an array. * @param listener The OnDataPointListener to receive sensor events. */ public void endFitDataSession( FitDataTypeSetting[] dataTypeSettings, OnDataPointListener listener) { if (mGoogleApiClient.isConnected()) { PendingResult pendingResult = Fitness.SessionsApi.stopSession(mGoogleApiClient, null); pendingResult.setResultCallback(new FitResultCallback( this, FitResultCallback.RegisterType.SESSION, null /* dataType */, false /* subscribe */)); for (FitDataTypeSetting dataTypeSetting : dataTypeSettings) { stopRecordingFitData(dataTypeSetting); unregisterFitDataListener(listener); } } } public boolean isSignedIn() { return (mGoogleApiClient != null && mGoogleApiClient.isConnected()); } public void userAuthenticated() { mAuthInProgress = false; } public boolean isClientReady() { // Make sure all the required sensors are registered. boolean hasUnregisteredSensor = false; for (FitDataTypeSetting fitDataTypeSetting : sensorsAwaitingRegistration) { if (fitDataTypeSetting.isRequired()) { hasUnregisteredSensor = true; break; } } return (mGoogleApiClient.isConnected() && !hasUnregisteredSensor); } public GoogleApiClient getGoogleApiClient() { return mGoogleApiClient; } protected void sensorRegistered(DataType dataType) { for (FitDataTypeSetting fitDataTypeSetting : sensorsAwaitingRegistration) { if (fitDataTypeSetting.getDataType().equals(dataType)) { sensorsAwaitingRegistration.remove(fitDataTypeSetting); break; } } } /** * Add RecordingApi listener for recording to GoogleFit backend. Can be called repeatedly on * multiple data types. * @param dataTypeSetting Type of data to listen to. */ private void startRecordingFitData(FitDataTypeSetting dataTypeSetting) { Fitness.RecordingApi.subscribe(mGoogleApiClient, dataTypeSetting.getDataType()) .setResultCallback(new FitResultCallback( this, FitResultCallback.RegisterType.RECORDING, dataTypeSetting.getDataType(), true)); } private void stopRecordingFitData(FitDataTypeSetting dataTypeSetting) { Fitness.RecordingApi.unsubscribe(mGoogleApiClient, dataTypeSetting.getDataType()) .setResultCallback(new FitResultCallback( this, FitResultCallback.RegisterType.RECORDING, dataTypeSetting.getDataType(), false)); } /** * Add SensorsApi listener for real-time display of sensor data. Can be called repeatedly on * multiple data types. * @param dataTypeSetting Type of data to listen to. * @param listener Listener for callbacks from SensorsApi. */ private void registerFitDataListener( FitDataTypeSetting dataTypeSetting, OnDataPointListener listener) { sensorsAwaitingRegistration.add(dataTypeSetting); Fitness.SensorsApi.add( mGoogleApiClient, new SensorRequest.Builder() .setDataType(dataTypeSetting.getDataType()) .setSamplingRate(dataTypeSetting.getSamplingRateSeconds(), TimeUnit.SECONDS) .setAccuracyMode(dataTypeSetting.getAccuracyMode()) .build(), listener) .setResultCallback(new FitResultCallback( this, FitResultCallback.RegisterType.SENSORS, dataTypeSetting.getDataType(), true)); } private void unregisterFitDataListener(OnDataPointListener listener) { Fitness.SensorsApi.remove(mGoogleApiClient, listener); } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/EndSummaryFragment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.gui; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import com.google.fpl.gim.examplegame.MainActivity; import com.google.fpl.gim.examplegame.R; import java.util.ArrayList; /** * Displays post-run summary. */ public class EndSummaryFragment extends Fragment { private ListView mFictionalProgressList; private ListView mFitnessStatisticsList; private boolean mGoogleFitConnected = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.end_screen, container, false); mFictionalProgressList = (ListView) rootView.findViewById(R.id.fictionalProgressList); mFitnessStatisticsList = (ListView) rootView.findViewById(R.id.fitnessStatisticsList); return rootView; } @Override public void onResume() { super.onResume(); if (mGoogleFitConnected) { ((MainActivity) getActivity()).setActionBarTitle(R.string.run_finish_text); } else { ((MainActivity) getActivity()).setActionBarTitle(R.string.fit_disconnected_text); } } public void displayStats(ArrayList fictionalProgress, ArrayList fitnessStatistics) { mFictionalProgressList.setAdapter(new ArrayAdapter<>(getActivity(), R.layout.menu_list_item, R.id.list_item_text, fictionalProgress)); mFitnessStatisticsList.setAdapter(new ArrayAdapter<>(getActivity(), R.layout.menu_list_item, R.id.list_item_text, fitnessStatistics)); } public void onFitStatusUpdated(boolean connected) { mGoogleFitConnected = connected; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/FitnessDataDisplayFragment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.gui; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.google.fpl.gim.examplegame.MainActivity; import com.google.fpl.gim.examplegame.Mission; import com.google.fpl.gim.examplegame.R; /** * Display fitness data during a run. */ public class FitnessDataDisplayFragment extends Fragment { private TextView mNumSteps; private TextView mMinutesPerMile; private TextView mTimeExercised; private TextView mWeaponChargedPercentage; private ProgressBar mProgressBar; private String mMissionName = "Mission"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.step_display, container, false); mNumSteps = (TextView) rootView.findViewById(R.id.num_steps_taken); mMinutesPerMile = (TextView) rootView.findViewById(R.id.minutes_per_mile); mTimeExercised = (TextView) rootView.findViewById(R.id.time_exercised); mWeaponChargedPercentage = (TextView) rootView.findViewById(R.id.percent_weapon_charged); mProgressBar = (ProgressBar) rootView.findViewById(R.id.circular_progress_bar); mProgressBar.setMax(100); mProgressBar.setProgress(0); return rootView; } @Override public void onResume() { super.onResume(); ((MainActivity)getActivity()).setActionBarTitle(mMissionName); } public void setNumSteps(int numSteps) { mNumSteps.setText(String.format("%d steps", numSteps)); } public void setMinutesPerMile(float minutesPerMile, float challengePace) { if (minutesPerMile >= Mission.getMaximumMinutesPerMile()) { mMinutesPerMile.setText(getActivity().getString(R.string.not_moving_speed)); } else { String minutesPerMileText = String.format("%.2f\nmins/mile", minutesPerMile); mMinutesPerMile.setText(minutesPerMileText); if (minutesPerMile <= challengePace) { mMinutesPerMile.setTextColor(getResources().getColor(R.color.green)); } else { mMinutesPerMile.setTextColor(getResources().getColor(R.color.red)); } } } public void setTimeExercised(int numMinutes, int numSeconds) { mTimeExercised.setText(String.format("%d:%02d", numMinutes, numSeconds)); } public void setWeaponChargedPercentage(int weaponChargedPercentage) { mWeaponChargedPercentage.setText(String.format("%d%%", weaponChargedPercentage)); mProgressBar.setProgress(weaponChargedPercentage); } public void setFitnessStats(Mission mission) { setNumSteps(mission.getNumSteps()); setMinutesPerMile(mission.getMinutesPerMile(), mission.getChallengePace()); setTimeExercised(mission.getNumMinutesExercised(), mission.getNumSecondsExercised()); setWeaponChargedPercentage(mission.getWeaponChargedPercentage()); } public void setMissionName(String missionName) { mMissionName = missionName; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/GameViews.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.gui; import android.app.Activity; import com.google.fpl.gim.examplegame.R; import com.google.fpl.gim.examplegame.gui.EndSummaryFragment; import com.google.fpl.gim.examplegame.gui.FitnessDataDisplayFragment; import com.google.fpl.gim.examplegame.gui.MissionSelectionFragment; import com.google.fpl.gim.examplegame.gui.MusicSelectionFragment; import com.google.fpl.gim.examplegame.gui.RunSpecificationSelectionFragment; import com.google.fpl.gim.examplegame.gui.StartMenuFragment; /** * Container for the game's UI Fragments. This class is implemented as a singleton to ensure that * only one instance of the GameViews class ever exists. */ public class GameViews { // Tags used to save/restore Fragments. public static final String START_MENU_TAG = "com.google.fpl.gim.examplegame.fragment.StartMenuFragment"; public static final String LIST_OF_MISSIONS_TAG = "com.google.fpl.gim.examplegame.ListOfMissionsFragment"; public static final String RUN_SPECIFICATIONS_TAG = "com.google.fpl.gim.examplegame.RunSpecificationsFragment"; public static final String MUSIC_SELECTION_TAG = "com.google.fpl.gim.examplegame.fragment.MusicSelectionFragment"; public static final String END_SUMMARY_TAG = "com.google.fpl.gim.examplegame.fragment.EndSummaryFragment"; public static final String FITNESS_DATA_DISPLAY_TAG = "com.google.fpl.gim.examplegame.fragment.FitnessDataDisplayFragment"; // UI Fragments. private StartMenuFragment mStartMenuFragment; private MissionSelectionFragment mMissionSelectionFragment; private RunSpecificationSelectionFragment mRunSpecificationsFragment; private MusicSelectionFragment mMusicSelectionFragment; private EndSummaryFragment mEndSummaryFragment; private FitnessDataDisplayFragment mFitnessDataDisplayFragment; public GameViews() { } /** * Called the first time upon starting the game by the 'initializeFragments' method in the Game * class. Creates fragments and attaches them to the Activity. */ public void initializeFragments(Activity activity) { mStartMenuFragment = new StartMenuFragment(); activity.getFragmentManager().beginTransaction() .add(R.id.container, mStartMenuFragment, START_MENU_TAG) .addToBackStack(START_MENU_TAG) .commit(); mStartMenuFragment.setRetainInstance(true); mMissionSelectionFragment = new MissionSelectionFragment(); mMissionSelectionFragment.setRetainInstance(true); mRunSpecificationsFragment = new RunSpecificationSelectionFragment(); mRunSpecificationsFragment.setRetainInstance(true); mMusicSelectionFragment = new MusicSelectionFragment(); mMusicSelectionFragment.setRetainInstance(true); mEndSummaryFragment = new EndSummaryFragment(); mEndSummaryFragment.setRetainInstance(true); mFitnessDataDisplayFragment = new FitnessDataDisplayFragment(); mFitnessDataDisplayFragment.setRetainInstance(true); } /** * Restores information and fragments from the Bundle upon lifecycle restart. Called * by the 'restoreFragments' method in the Game class. */ public void restoreFragments(Activity activity) { StartMenuFragment foundStartMenuFragment = (StartMenuFragment) activity.getFragmentManager() .findFragmentByTag(START_MENU_TAG); if (foundStartMenuFragment != null) { mStartMenuFragment = foundStartMenuFragment; } else { mStartMenuFragment = new StartMenuFragment(); } MissionSelectionFragment foundMissionSelectionFragment = (MissionSelectionFragment) activity.getFragmentManager() .findFragmentByTag(LIST_OF_MISSIONS_TAG); if (foundMissionSelectionFragment != null) { mMissionSelectionFragment = foundMissionSelectionFragment; } else { mMissionSelectionFragment = new MissionSelectionFragment(); } RunSpecificationSelectionFragment foundRunSpecificationSelectionFragment = (RunSpecificationSelectionFragment) activity.getFragmentManager() .findFragmentByTag(RUN_SPECIFICATIONS_TAG); if (foundRunSpecificationSelectionFragment != null) { mRunSpecificationsFragment = foundRunSpecificationSelectionFragment; } else { mRunSpecificationsFragment = new RunSpecificationSelectionFragment(); } MusicSelectionFragment foundMusicSelectionFragment = (MusicSelectionFragment) activity.getFragmentManager() .findFragmentByTag(MUSIC_SELECTION_TAG); if (foundMissionSelectionFragment != null) { mMusicSelectionFragment = foundMusicSelectionFragment; } else { mMusicSelectionFragment = new MusicSelectionFragment(); } EndSummaryFragment foundEndSummaryFragment = (EndSummaryFragment) activity.getFragmentManager() .findFragmentByTag(END_SUMMARY_TAG); if (foundEndSummaryFragment != null) { mEndSummaryFragment = foundEndSummaryFragment; } else { mEndSummaryFragment = new EndSummaryFragment(); } FitnessDataDisplayFragment foundFitnessDataDisplayFragment = (FitnessDataDisplayFragment) activity.getFragmentManager() .findFragmentByTag(FITNESS_DATA_DISPLAY_TAG); if (foundFitnessDataDisplayFragment != null) { mFitnessDataDisplayFragment = foundFitnessDataDisplayFragment; } else { mFitnessDataDisplayFragment = new FitnessDataDisplayFragment(); } } public StartMenuFragment getStartMenuFragment() { return this.mStartMenuFragment; } public MissionSelectionFragment getListOfMissionsFragment() { return mMissionSelectionFragment; } public RunSpecificationSelectionFragment getRunSpecificationsFragment() { return mRunSpecificationsFragment; } public MusicSelectionFragment getMusicSelectionFragment() { return mMusicSelectionFragment; } public EndSummaryFragment getEndSummaryFragment() { return mEndSummaryFragment; } public FitnessDataDisplayFragment getFitnessDataDisplayFragment() { return mFitnessDataDisplayFragment; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/MissionSelectionFragment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.gui; import android.app.Fragment; import android.app.ListFragment; import android.content.res.AssetManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import com.google.fpl.gim.examplegame.MainActivity; import com.google.fpl.gim.examplegame.utils.MissionParseException; import com.google.fpl.gim.examplegame.utils.MissionParser; import com.google.fpl.gim.examplegame.R; import com.google.fpl.gim.examplegame.utils.Utils; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; /** * A UI fragment that represents the game's mission selection screen. No data is stored in this * fragment. */ public class MissionSelectionFragment extends ListFragment { private static final String TAG = MissionSelectionFragment.class.getSimpleName(); private ArrayList mAssetNames = new ArrayList<>(); private ArrayList mMissionNames = new ArrayList<>(); private String mSelectedMissionName; private String mSelectedAssetPath; private static final String MISSION_ASSET_FOLDER_NAME = "missions"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (mMissionNames.size() == 0) { // Needs access to a Context in order to access the assets folder. AssetManager assetManager = getActivity().getAssets(); String[] missionFileNames = new String[0]; try { // Obtain the files in assets/missions. missionFileNames = assetManager.list(MISSION_ASSET_FOLDER_NAME); } catch (IOException e) { e.printStackTrace(); } // Open the missions to obtain plain text names. for (String missionFileName : missionFileNames) { // Open a stream for the mission. InputStream stream; try { // All missions should be in the assets/missions folder. ArrayList subDirectories = new ArrayList<>(); subDirectories.add(missionFileName); stream = assetManager .open(Utils.makeFilePath(MISSION_ASSET_FOLDER_NAME, subDirectories)); } catch (IOException e) { e.printStackTrace(); continue; } // Find the mission name. String missionName; try { missionName = MissionParser.getMissionName(stream); } catch (MissionParseException e) { e.printStackTrace(); missionName = "Description failed."; } // Close the stream. try { stream.close(); } catch (IOException e) { e.printStackTrace(); } mMissionNames.add(missionName); mAssetNames.add(missionFileName); } } setListAdapter(new ArrayAdapter<>(getActivity(), R.layout.menu_list_item, R.id.list_item_text, mMissionNames)); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.menu_mission_list, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); } @Override public void onListItemClick(ListView l, View v, int position, long id) { onMissionSelected(position); } @Override public void onResume() { super.onResume(); ((MainActivity)getActivity()).setActionBarTitle(R.string.select_mission_title); } public void onMissionSelected(int position) { Utils.logDebug(TAG, "onMissionSelected - Mission #" + (position + 1) + " has been selected!"); mSelectedMissionName = mMissionNames.get(position); ArrayList subDirectories = new ArrayList<>(); subDirectories.add(mAssetNames.get(position)); mSelectedAssetPath = Utils.makeFilePath(MISSION_ASSET_FOLDER_NAME, subDirectories); // Display RunSpecificationSelectionFragment. Fragment runSpecificationsFragment = ((MainActivity) getActivity()).getGameViews().getRunSpecificationsFragment(); getActivity().getFragmentManager().beginTransaction() .setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left) .remove(this) .add(R.id.container, runSpecificationsFragment, GameViews.RUN_SPECIFICATIONS_TAG) .addToBackStack(null) .commit(); } public String getSelectedMissionName() { return mSelectedMissionName; } public String getSelectedAssetPath() { return mSelectedAssetPath; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/MusicSelectionFragment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.gui; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.google.fpl.gim.examplegame.MainActivity; import com.google.fpl.gim.examplegame.R; /** * A fragment notifying the user to go select music to listen to during their run. */ public class MusicSelectionFragment extends Fragment { private static final String TAG = MusicSelectionFragment.class.getSimpleName(); private Button mReadyButton; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.menu_music_selection, container, false); mReadyButton = (Button) rootView.findViewById(R.id.start_mission_button); mReadyButton.setEnabled(true); mReadyButton.setText(R.string.start_mission_button); return rootView; } @Override public void onResume() { super.onResume(); ((MainActivity)getActivity()).setActionBarTitle(R.string.select_music_title); } public void disableReadyButton() { mReadyButton.setEnabled(false); mReadyButton.setText(R.string.start_mission_pressed); } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/NotificationOptions.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.gui; import android.support.v4.app.NotificationCompat; import com.google.fpl.gim.examplegame.R; /** * Options to build a notification from. Subset of all options that an Android notification may * have. */ public class NotificationOptions { private int mNotificationId; private int mSmallIconResourceId; private String mTitle; private String mContent; private NotificationCompat.Action[] mActions = null; private int mNotificationDefaults; private int mNotificationPriority; private long[] mVibratePattern; private static final int DEFAULT_ID = 1234; private static final int DEFAULT_SMALL_ICON_RESOURCE_ID = R.drawable.ic_notification; private static final String DEFAULT_TITLE = "Enemy!"; private static final String DEFAULT_CONTENT = "An enemy appeared, what will you do?"; // Phone notification settings for vibration, sound, and lights. private static final int APP_NOTIFICATION_DEFAULTS = NotificationCompat.DEFAULT_ALL; // Maximum priority, so it will be the first notification on the wearable device. private static final int DEFAULT_PRIORITY = NotificationCompat.PRIORITY_DEFAULT; /** * Default constructor. */ public NotificationOptions() { } /** * Constructor to set all build options at creation. */ public NotificationOptions(int notificationId, int smallIconResourceId, String title, String content, NotificationCompat.Action[] actions, int notificationDefaults, int notificationPriority, long[] vibratePattern) { this.mNotificationId = notificationId; this.mSmallIconResourceId = smallIconResourceId; this.mTitle = title; this.mContent = content; this.mActions = actions; this.mNotificationDefaults = notificationDefaults; this.mNotificationPriority = notificationPriority; this.mVibratePattern = vibratePattern; } /** * Statically create default build options. * * @return Default build options for a notification. */ public static NotificationOptions getDefaultNotificationOptions() { NotificationOptions options = new NotificationOptions(); options.mNotificationId = DEFAULT_ID; options.mSmallIconResourceId = DEFAULT_SMALL_ICON_RESOURCE_ID; options.mTitle = DEFAULT_TITLE; options.mContent = DEFAULT_CONTENT; options.mNotificationDefaults = APP_NOTIFICATION_DEFAULTS; options.mNotificationPriority = DEFAULT_PRIORITY; return options; } /** * Small icon, title, and text must be set for all notifications. * * @param smallIconResourceId The resource Id of a picture to use as the small icon. * @param title A string to use as the notification title. * @param content A string to use as the notification content. */ public void setRequiredOptions(int smallIconResourceId, String title, String content) { this.mSmallIconResourceId = smallIconResourceId; this.mTitle = title; this.mContent = content; } /** * Set actions for this notification. * * @param actions Actions associated with the notification. */ public void setActions(NotificationCompat.Action[] actions) { this.mActions = actions; } /** * Notification defaults are ringtones, vibration patterns, and LED colors for the notification. * * @param notificationDefaults Defaults to use for this notification. */ public void setNotificationDefaults(int notificationDefaults) { this.mNotificationDefaults = notificationDefaults; } /** * Priority determines the notification's position in the notification list.\ * @param notificationPriority Priority to use for this notification. */ public void setNotificationPriority(int notificationPriority) { this.mNotificationPriority = notificationPriority; } public void setNotificationId(int id) { this.mNotificationId = id; } public void setPriorityAsDefault() { mNotificationPriority = NotificationCompat.PRIORITY_DEFAULT; } public void setPriorityAsHigh() { mNotificationPriority = NotificationCompat.PRIORITY_HIGH; } public void setPriorityAsMax() { mNotificationPriority = NotificationCompat.PRIORITY_MAX; } public void setContent(String content) { this.mContent = content; } public void setTitle(String title) { this.mTitle = title; } public void setVibratePattern(long[] vibratePattern) { this.mVibratePattern = vibratePattern; } public int getNotificationPriority() { return mNotificationPriority; } public int getNotificationId() { return mNotificationId; } public int getSmallIconResourceId() { return mSmallIconResourceId; } public String getTitle() { return mTitle; } public String getContent() { return mContent; } public NotificationCompat.Action[] getActions() { return mActions; } public int getNotificationDefaults() { return mNotificationDefaults; } public long[] getVibratePattern() { return mVibratePattern; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/RunSpecificationSelectionFragment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.gui; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar; import android.widget.TextView; import com.google.fpl.gim.examplegame.MainActivity; import com.google.fpl.gim.examplegame.R; /** * A UI Fragment that represents the game's run specification selection screen. */ public class RunSpecificationSelectionFragment extends Fragment { private static final String TAG = RunSpecificationSelectionFragment.class.getSimpleName(); // The minimum allowed challenge pace. private static final float CHALLENGE_PACE_MIN_MINUTES_PER_MILE = 8f; // The maximum allowed challenge pace. private static final float CHALLENGE_PACE_MAX_MINUTES_PER_MILE = 30f; // The range of the challenge pace. private static final float CHALLENGE_PACE_RANGE_MINUTES_PER_MILE = CHALLENGE_PACE_MAX_MINUTES_PER_MILE - CHALLENGE_PACE_MIN_MINUTES_PER_MILE; // The default challenge pace. private static final float CHALLENGE_PACE_DEFAULT_MINUTES_PER_MILE = 20f; private static final int CHALLENGE_PACE_INCREMENTS_PER_MINUTE = 4; // The maximum value of the challenge pace seek bar. private static final int CHALLENGE_PACE_SEEK_BAR_MAX = (int) CHALLENGE_PACE_RANGE_MINUTES_PER_MILE * CHALLENGE_PACE_INCREMENTS_PER_MINUTE; // The default value for the progress bar.(int)( private static final int CHALLENGE_PACE_PROGRESS_BAR_DEFAULT = (int) ( (1.0f - (CHALLENGE_PACE_DEFAULT_MINUTES_PER_MILE - CHALLENGE_PACE_MIN_MINUTES_PER_MILE) / CHALLENGE_PACE_RANGE_MINUTES_PER_MILE) * CHALLENGE_PACE_SEEK_BAR_MAX); private static final float MISSION_LENGTH_MINUTES = 30.0f; private static final float INTERVAL_LENGTH_MINUTES = 1.5f; // SeekBar for selecting a challenge pace. SeekBar mChallengePaceSeekBar; // Text display of the current selected challenge pace. TextView mChallengePaceText; private float mSelectedMissionLengthMinutes; private float mSelectedIntervalLengthMinutes; private float mSelectedChallengePaceMinutesPerMile; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.menu_run_specifications, container, false); mChallengePaceSeekBar = (SeekBar) rootView.findViewById(R.id.challenge_speed_field); mChallengePaceSeekBar.setMax(CHALLENGE_PACE_SEEK_BAR_MAX); mChallengePaceSeekBar.setProgress(CHALLENGE_PACE_PROGRESS_BAR_DEFAULT); mChallengePaceSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateChallengePaceText(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mChallengePaceText = (TextView) rootView.findViewById(R.id.challenge_speed_text); updateChallengePaceText(CHALLENGE_PACE_PROGRESS_BAR_DEFAULT); return rootView; } @Override public void onResume() { super.onResume(); ((MainActivity)getActivity()).setActionBarTitle(R.string.run_specification_title); } public void onEnterPressed() { // Currently does not query the user for a run length. Assume each mission is 30 minutes. mSelectedMissionLengthMinutes = MISSION_LENGTH_MINUTES; // Currently does not query the user for an interval length. Assume each interval is 1.5 // minutes. mSelectedIntervalLengthMinutes = INTERVAL_LENGTH_MINUTES; mSelectedChallengePaceMinutesPerMile = calculateChallengePaceFromProgress(mChallengePaceSeekBar.getProgress()); // Display MusicSelectionFragment. Fragment musicSelectionFragment = ((MainActivity) getActivity()).getGameViews().getMusicSelectionFragment(); getActivity().getFragmentManager().beginTransaction() .setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left) .remove(this) .add(R.id.container, musicSelectionFragment, GameViews.MUSIC_SELECTION_TAG) .addToBackStack(null) .commit(); } /** * Displays the currently selected Challenge Pace based on SeekBar progress. * @param progress Int representing progress from 0 to CHALLENGE_PACE_SEEK_BAR_MAX. */ private void updateChallengePaceText(int progress) { float minutesPerMile = calculateChallengePaceFromProgress(progress); String formattedText = String.format(getActivity() .getString(R.string.challenge_speed_display), minutesPerMile); mChallengePaceText.setText(formattedText); } /** * Calculates Challenge Pace based on SeekBar progress. * @param progress Int representing progress from 0 to CHALLENGE_PACE_SEEK_BAR_MAX. * @return A challenge pace in minutes per mile. */ private float calculateChallengePaceFromProgress(int progress) { return CHALLENGE_PACE_MIN_MINUTES_PER_MILE + ((1.0f - ((float) progress) / CHALLENGE_PACE_SEEK_BAR_MAX) * CHALLENGE_PACE_RANGE_MINUTES_PER_MILE); } public float getSelectedMissionLengthMinutes() { return mSelectedMissionLengthMinutes; } public float getSelectedIntervalLengthMinutes() { return mSelectedIntervalLengthMinutes; } public float getSelectedChallengePaceMinutesPerMile() { return mSelectedChallengePaceMinutesPerMile; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/StartMenuFragment.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.gui; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.google.fpl.gim.examplegame.MainActivity; import com.google.fpl.gim.examplegame.R; import com.google.fpl.gim.examplegame.utils.Utils; /** * A UI fragment that represents the game's start screen. No data is stored in this fragment. */ public class StartMenuFragment extends Fragment { private static final String TAG = StartMenuFragment.class.getSimpleName(); private Button mStartButton; private boolean isGoogleFitConnected; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.menu_start, container, false); mStartButton = (Button) rootView.findViewById(R.id.start_button); updateStartButton(); return rootView; } @Override public void onResume() { super.onResume(); ((MainActivity)getActivity()).setActionBarTitle(R.string.app_name); } public void onStartButtonPressed() { Utils.logDebug(TAG, "onStartButtonPressed"); // Display MissionSelectionFragment MissionSelectionFragment missionSelectionFragment = ((MainActivity) getActivity()).getGameViews().getListOfMissionsFragment(); getActivity().getFragmentManager().beginTransaction() .setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left) .remove(this) .add(R.id.container, missionSelectionFragment, GameViews.LIST_OF_MISSIONS_TAG) .addToBackStack(null) .commit(); } public void onFitStatusUpdated(boolean connected) { isGoogleFitConnected = connected; updateStartButton(); } private void updateStartButton() { if (isGoogleFitConnected) { mStartButton.setEnabled(true); mStartButton.setText(R.string.start_button_ready); } else { mStartButton.setEnabled(false); mStartButton.setText(R.string.start_button_not_connected); } } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/utils/MissionParseException.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.utils; /** * An exception for problems during the parsing of a mission. */ public class MissionParseException extends Exception { private static final String MOMENT_TYPE_EXCEPTION = "Mission could not be parsed."; public MissionParseException() { super(MOMENT_TYPE_EXCEPTION); } public MissionParseException(String s) { super(s); } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/utils/MissionParser.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.utils; import android.net.Uri; import com.google.fpl.gim.examplegame.Choice; import com.google.fpl.gim.examplegame.ChoiceMoment; import com.google.fpl.gim.examplegame.ChoiceMomentData; import com.google.fpl.gim.examplegame.Mission; import com.google.fpl.gim.examplegame.Moment; import com.google.fpl.gim.examplegame.Outcome; import com.google.fpl.gim.examplegame.SfxMoment; import com.google.fpl.gim.examplegame.SfxMomentData; import com.google.fpl.gim.examplegame.SpokenTextMoment; import com.google.fpl.gim.examplegame.SpokenTextMomentData; import com.google.fpl.gim.examplegame.TimerMoment; import com.google.fpl.gim.examplegame.TimerMomentData; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; /** * A class for parsing a mission in a file. */ public class MissionParser { private static final String TAG = MissionParser.class.getSimpleName(); private static final String ELEMENT_MISSION = "mission"; private static final String MISSION_ATTRIBUTE_START_ID = "start_id"; private static final String MISSION_ATTRIBUTE_NAME = "name"; private static final String ELEMENT_MOMENT = "moment"; // Types of moments. private static final String MOMENT_TYPE_TIMER = "timer"; private static final String MOMENT_TYPE_SFX = "sfx"; private static final String MOMENT_TYPE_SPOKEN_TEXT = "spoken_text"; private static final String MOMENT_TYPE_CHOICE = "choice"; // Attributes for all moments. private static final String MOMENT_ATTRIBUTE_TYPE = "type"; private static final String MOMENT_ATTRIBUTE_ID = "id"; // Attributes for specific types of moments. private static final String ELEMENT_CHOICE = "choice"; private static final String ELEMENT_DESCRIPTION = "description"; private static final String ELEMENT_NEXT_MOMENT = "next_moment"; private static final String NEXT_MOMENT_ATTRIBUTE_ID = "id"; private static final String ELEMENT_LENGTH_MINUTES = "length_minutes"; private static final String ELEMENT_TIMEOUT_LENGTH_MINUTES = "timeout_length_minutes"; private static final String ELEMENT_DEFAULT_CHOICE = "default_choice"; private static final String ELEMENT_URI = "uri"; private static final String DEFAULT_CHOICE_ATTRIBUTE_ID = "id"; private static final String ELEMENT_OUTCOME = "outcome"; private static final String CHOICE_ATTRIBUTE_ID = "id"; private static final String ELEMENT_TEXT_TO_SPEAK = "text_to_speak"; private static final String ELEMENT_FICTIONAL_PROGRESS = "fictional_progress"; private static final String ELEMENT_ICON = "icon"; private static final String ICON_ATTRIBUTE_NAME = "name"; // Attributes for outcomes. private static final String OUTCOME_ATTRIBUTE_DEPLETE_WEAPON = "deplete_weapon"; private static final String OUTCOME_ATTRIBUTE_INCREMENT_ENEMIES = "increment_enemies"; // ID that signifies the moment whose next is this is an ending moment. private static final String DEFAULT_END_ID = null; // ID that signifies that this Choice should only be displayed when the user's weapon is // charged. public static final String FIRE_WEAPON_CHOICE_ID = "fire"; /** * Adds the Moments that define a Mission to that Mission by reading from input. Assumes * XML file. * @param missionStream The InputStream to read from. * @param mission The Mission object to add Moments to. * @throws MissionParseException */ public static void parseMission(InputStream missionStream, Mission mission) throws MissionParseException { Document doc = getDocumentFromInputStream(missionStream); doc.getDocumentElement().normalize(); // Find the Mission's starting Moment. NodeList missionNodes = doc.getElementsByTagName(ELEMENT_MISSION); String startId = null; for (int i = 0; i < missionNodes.getLength(); i++) { Node missionNode = missionNodes.item(i); if (isElementNode(missionNode)) { startId = ((Element) missionNode).getAttribute(MISSION_ATTRIBUTE_START_ID); Utils.logDebug(TAG, "Start id is \"" + startId + "\"."); break; } } mission.setFirstMomentId(startId); // Each Moment is represented as an Element NodeList momentsList = doc.getElementsByTagName(ELEMENT_MOMENT); for (int i = 0; i < momentsList.getLength(); i++) { Node momentNode = momentsList.item(i); // We check to make sure that we have Elements, though getElementsByTagName should // provide only Elements. if (isElementNode(momentNode)) { Moment moment; Element momentElement = (Element) momentNode; // Data for all Moments String id = momentElement.getAttribute(MOMENT_ATTRIBUTE_ID); String momentType = momentElement.getAttribute(MOMENT_ATTRIBUTE_TYPE); // Ideally would use Java 7 to switch on the strings themselves, but // project is not configured to use Java 7. if (momentType.equals(MOMENT_TYPE_CHOICE)) { Utils.logDebug(TAG, "Choice moment created."); ChoiceMomentData momentData = parseChoiceMomentElement(id, momentElement); moment = new ChoiceMoment(mission, momentData); } else if (momentType.equals(MOMENT_TYPE_SFX)) { Utils.logDebug(TAG, "Sfx moment created."); SfxMomentData momentData = parseSfxMoment(id, momentElement); moment = new SfxMoment(mission, momentData); } else if (momentType.equals(MOMENT_TYPE_TIMER)) { Utils.logDebug(TAG, "Timer moment created."); TimerMomentData momentData = parseTimerMoment(id, momentElement); moment = new TimerMoment(mission, momentData); } else if (momentType.equals(MOMENT_TYPE_SPOKEN_TEXT)) { Utils.logDebug(TAG, "Spoken text moment created."); SpokenTextMomentData momentData = parseSpokenTextMoment(id, momentElement); moment = new SpokenTextMoment(mission, momentData); } else { throw new MissionParseException("Moment type invalid."); } mission.addMoment(id, moment); } } } /** * Everything in an XML document is represented as a Document Object Model Node. Elements are * defined between opening and closing tags, for example "". * @param node a DOM Node from a Document * @return true if the DOM Node is an Element. */ private static boolean isElementNode(Node node) { return node.getNodeType() == Node.ELEMENT_NODE; } /** * Parses an Element representing an SfxMoment to create SfxMomentData. * @param momentId Already parsed data about the Moment. * @param momentElement the DOM Element to be parsed. * @return data to construct an SfxMoment */ private static SfxMomentData parseSfxMoment(String momentId, Element momentElement) throws MissionParseException { Uri uri = parseUriElement(findSingleChildElementByTag(momentElement, ELEMENT_URI)); String nextMomentId = getNextMomentId(momentElement); ArrayList fictionalProgress = parseMomentFictionalProgress(momentElement); return new SfxMomentData(momentId, nextMomentId, fictionalProgress, uri); } /** * Parses an Element representing a TimerMoment to create TimerMomentData. * @param momentId Already parsed data about the Moment. * @param momentElement the DOM Element to be parsed. * @return data to construct a TimerMoment */ private static TimerMomentData parseTimerMoment(String momentId, Element momentElement) throws MissionParseException { float momentLengthMinutes = parseLengthMinutesElement( findSingleChildElementByTag(momentElement, ELEMENT_LENGTH_MINUTES)); String nextMomentId = getNextMomentId(momentElement); ArrayList fictionalProgress = parseMomentFictionalProgress(momentElement); return new TimerMomentData(momentId, nextMomentId, fictionalProgress, momentLengthMinutes); } /** * Parses an Element representing a SpokenTextMoment to create SpokenTextMomentData. * @param momentId Already parsed data about the Moment. * @param momentElement the DOM Element to be parsed. * @return data to construct an SpokenTextMoment */ private static SpokenTextMomentData parseSpokenTextMoment(String momentId, Element momentElement) throws MissionParseException { String textToSpeak = parseTextToSpeakElement( findSingleChildElementByTag(momentElement, ELEMENT_TEXT_TO_SPEAK)); String nextMomentId = getNextMomentId(momentElement); ArrayList fictionalProgress = parseMomentFictionalProgress(momentElement); return new SpokenTextMomentData(momentId, nextMomentId, fictionalProgress, textToSpeak); } /** * Parses an Element representing a ChoiceMoment to create ChoiceMomentData. * @param momentId Already parsed data about the Moment. * @param momentElement the DOM Element to be parsed. * @return data to construct an ChoiceMoment */ private static ChoiceMomentData parseChoiceMomentElement(String momentId, Element momentElement) throws MissionParseException { String description = getDescription(momentElement); float timeoutLengthMinutes = parseTimeoutLengthMinutesElement( findSingleChildElementByTag(momentElement, ELEMENT_TIMEOUT_LENGTH_MINUTES)); String defaultChoiceId = parseDefaultChoiceElement( findSingleChildElementByTag(momentElement, ELEMENT_DEFAULT_CHOICE)); ArrayList fictionalProgress = parseMomentFictionalProgress(momentElement); ChoiceMomentData data = new ChoiceMomentData(momentId, fictionalProgress, description, defaultChoiceId, timeoutLengthMinutes); NodeList choiceNodes = momentElement.getElementsByTagName(ELEMENT_CHOICE); if (choiceNodes.getLength() > ChoiceMoment.MAXIMUM_NUM_OF_CHOICES) { throw new MissionParseException("ChoiceMoments can have no more than " + ChoiceMoment.MAXIMUM_NUM_OF_CHOICES + " Choices."); } if (choiceNodes.getLength() < ChoiceMoment.MINIMUM_NUM_OF_CHOICES) { throw new MissionParseException("ChoiceMoments can have no fewer than " + ChoiceMoment.MINIMUM_NUM_OF_CHOICES + " Choices."); } boolean defaultChoiceIsExistingChoice = false; for (int i = 0; i < choiceNodes.getLength(); i++) { Node choiceNode = choiceNodes.item(i); if (isElementNode(choiceNode)) { Choice choice = parseChoiceElement((Element) choiceNode); if (choice.getChoiceId() == defaultChoiceId || choice.getChoiceId().equals(defaultChoiceId)) { defaultChoiceIsExistingChoice = true; } data.addChoice(choice); } } if (!defaultChoiceIsExistingChoice) { throw new MissionParseException("Default choice ID is not a valid Choice."); } return data; } /** * Creates a Choice from a DOM Element representing a Choice. * @param choiceElement The DOM element representing a Choice. * @return a Choice as defined in the DOM Element. */ private static Choice parseChoiceElement(Element choiceElement) throws MissionParseException { String id = choiceElement.getAttribute(CHOICE_ATTRIBUTE_ID); String description = getDescription(choiceElement); String nextMomentId = getNextMomentId(choiceElement); Outcome outcome = parseOutcomeElement(findSingleChildElementByTag(choiceElement, ELEMENT_OUTCOME)); boolean requiresChargedWeapon = false; if (id.equals(MissionParser.FIRE_WEAPON_CHOICE_ID)) { requiresChargedWeapon = true; } ArrayList fictionalProgress = parseNestedFictionalProgress(choiceElement); String iconName = parseIconElement(findSingleChildElementByTag(choiceElement, ELEMENT_ICON)); return new Choice(id, description, nextMomentId, outcome, requiresChargedWeapon, fictionalProgress, iconName); } /** * Creates an Outcome from a DOM Element representing an Outcome. * @param outcomeElement The DOM element representing an Outcome. * @return an Outcome as defined in the DOM Element. */ private static Outcome parseOutcomeElement(Element outcomeElement) { boolean depleteWeapon = Boolean.valueOf(outcomeElement.getAttribute(OUTCOME_ATTRIBUTE_DEPLETE_WEAPON)); boolean incrementEnemies = Boolean.valueOf(outcomeElement.getAttribute(OUTCOME_ATTRIBUTE_INCREMENT_ENEMIES)); return new Outcome(depleteWeapon, incrementEnemies); } /** * Given an XML element that has a nested next_moment element, finds the next moment ID. * @param element An XML element. * @return The next moment ID for the element. */ private static String getNextMomentId(Element element) throws MissionParseException { Element nextMomentElement = findSingleChildElementByTag(element, ELEMENT_NEXT_MOMENT); // If the element does not have a next moment, then set to the default end signifier. if (nextMomentElement == null) { return DEFAULT_END_ID; } return parseNextMomentElement(nextMomentElement); } /** * Given an XML element that has a nested description element, finds the description. * @param element An XML element. * @return The description for the element. */ private static String getDescription(Element element) throws MissionParseException { return parseDescriptionElement(findSingleChildElementByTag(element, ELEMENT_DESCRIPTION)); } /** * Finds the first occurrence of a child Element of a given tag within a parent's tree. * @param parent An Element with child Elements * @param tag The Element to find * @return The first occurrence of an Element of type tag within the parent's child tree. */ private static Element findSingleChildElementByTag(Element parent, String tag) throws MissionParseException { Node node = null; NodeList nodes = parent.getElementsByTagName(tag); for (int i = 0; i < nodes.getLength(); i++) { node = nodes.item(i); if (isElementNode(node)) { break; } node = null; } // All attributes are required except the 'next_moment' attribute. The lack of a // 'next_moment' attribute signifies that the moment is the last moment in the mission. if (!tag.equals(ELEMENT_NEXT_MOMENT) && node == null) { throw new MissionParseException(tag + " could not be found."); } return (Element) node; } private static String parseNextMomentElement(Element nextMomentElement) { String nextMomentId = nextMomentElement.getAttribute(NEXT_MOMENT_ATTRIBUTE_ID); if (nextMomentId == null || nextMomentId.equals("")) { return DEFAULT_END_ID; } return nextMomentId; } private static float parseLengthMinutesElement(Element lengthMinutesElement) throws MissionParseException { Node node = lengthMinutesElement.getFirstChild(); if (node == null) { throw new MissionParseException("Length minutes element could not be found."); } return Float.parseFloat(node.getTextContent()); } private static Uri parseUriElement(Element uriElement) throws MissionParseException { Node node = uriElement.getFirstChild(); if (node == null) { throw new MissionParseException("URI element could not be found."); } return Uri.parse(node.getTextContent()); } private static String parseTextToSpeakElement(Element textToSpeakElement) throws MissionParseException { Node node = textToSpeakElement.getFirstChild(); if (node == null) { throw new MissionParseException("Text to speak element could not be found."); } return node.getTextContent(); } private static String parseDescriptionElement(Element descriptionElement) throws MissionParseException { Node node = descriptionElement.getFirstChild(); if (node == null) { throw new MissionParseException("Description element could not be found."); } return descriptionElement.getTextContent(); } private static float parseTimeoutLengthMinutesElement(Element timeoutLengthMinutesElement) throws MissionParseException { Node node = timeoutLengthMinutesElement.getFirstChild(); if (node == null) { throw new MissionParseException("Timeout length minutes element could not be found."); } return Float.parseFloat(timeoutLengthMinutesElement.getFirstChild().getTextContent()); } private static String parseDefaultChoiceElement(Element defaultChoiceElement) throws MissionParseException { String defaultChoice = defaultChoiceElement.getAttribute(DEFAULT_CHOICE_ATTRIBUTE_ID); if (defaultChoice == null) { throw new MissionParseException("Default choice element could not be found."); } if (defaultChoice.equals(FIRE_WEAPON_CHOICE_ID)) { throw new MissionParseException("Default choice cannot be 'fire'."); } return defaultChoice; } /** * Determines the name of a mission. * @param missionStream InputStream to read from. * @return A string of the name of the mission. Empty string if a name is not specified. * @throws MissionParseException */ public static String getMissionName(InputStream missionStream) throws MissionParseException { Document doc = getDocumentFromInputStream(missionStream); doc.getDocumentElement().normalize(); NodeList missionNodes = doc.getElementsByTagName(ELEMENT_MISSION); String missionName; for (int i = 0; i < missionNodes.getLength(); i++) { Node missionNode = missionNodes.item(i); if (isElementNode(missionNode)) { // Gives an empty string if the attribute is missing. missionName = ((Element) missionNode).getAttribute(MISSION_ATTRIBUTE_NAME); if (missionName.equals("")) { throw new MissionParseException("Mission name missing."); } Utils.logDebug(TAG, "Mission name is " + missionName); return missionName; } } // No Element Node for Mission. throw new MissionParseException("Mission element could not be found."); } /** * Creates a Document given an InputStream. * @param missionStream The stream to open a document from. * @return The document, successfully parsed from xml. * @throws MissionParseException */ private static Document getDocumentFromInputStream(InputStream missionStream) throws MissionParseException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); throw new MissionParseException("ParserConfigurationException while reading mission."); } Document doc; try { doc = builder.parse(missionStream); } catch (SAXException e) { e.printStackTrace(); throw new MissionParseException("SAXException while reading mission."); } catch (IOException e) { e.printStackTrace(); throw new MissionParseException("IOException while reading mission."); } return doc; } /** * Determines the Fictional Progress strings associated with a moment. * @param momentElement The moment to parse. * @return A list of Fictional Progress strings. */ private static ArrayList parseMomentFictionalProgress(Element momentElement) throws MissionParseException { ArrayList progress = new ArrayList<>(); NodeList fictionalProgressNodes = momentElement.getElementsByTagName(ELEMENT_FICTIONAL_PROGRESS); for (int i = 0; i < fictionalProgressNodes.getLength(); i++) { Node node = fictionalProgressNodes.item(i); Element parent = (Element) node.getParentNode(); if (isElementNode(node) && parent.getTagName().equals(ELEMENT_MOMENT)) { String progressString = parseFictionalProgressElement((Element) node); progress.add(progressString); } } return progress; } private static String parseFictionalProgressElement(Element element) throws MissionParseException { Node node = element.getFirstChild(); if (node == null) { throw new MissionParseException("Fictional Progress Element not found"); } String progressString = element.getFirstChild().getTextContent(); if (progressString.equals("")) { throw new MissionParseException("Fictional Progress empty."); } return progressString; } private static ArrayList parseNestedFictionalProgress(Element parent) throws MissionParseException { ArrayList progressStrings = new ArrayList<>(); NodeList nodeList = parent.getElementsByTagName(ELEMENT_FICTIONAL_PROGRESS); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (isElementNode(node)) { String progressString = parseFictionalProgressElement((Element) node); progressStrings.add(progressString); } } return progressStrings; } private static String parseIconElement(Element iconElement) throws MissionParseException { String iconResourceName = iconElement.getAttribute(ICON_ATTRIBUTE_NAME); if (iconResourceName == null || iconResourceName.equals("")) { throw new MissionParseException("Icon element has no name attribute."); } return iconResourceName; } } ================================================ FILE: app/src/main/java/com/google/fpl/gim/examplegame/utils/Utils.java ================================================ /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fpl.gim.examplegame.utils; import android.util.Log; import com.google.fpl.gim.examplegame.BuildConfig; import java.io.File; import java.util.ArrayList; /** * A few utility functions and classes used by the prototype. */ public class Utils { public static final float SECONDS_TO_NANOS_SCALE = (float) Math.pow(10, 9); public static final float NANOS_TO_SECONDS_SCALE = (float) Math.pow(10, -9); public static final int MINUTES_TO_SECONDS_SCALE = 60; public static final float SECONDS_TO_MINUTES_SCALE = 1.0f / 60; public static final float MILES_TO_FEET_SCALE = 5280f; public static final float SECONDS_PER_METER_TO_MINUTES_PER_MILE_SCALE = 26.8224f; // user control for displaying log messages private static final boolean DEBUG_LOG = true; public static float nanosToSeconds(long nanos) { return nanos / SECONDS_TO_NANOS_SCALE; } public static long secondsToNanos(float seconds) { return (long) (seconds * SECONDS_TO_NANOS_SCALE); } public static long minutesToNanos(float min) { return (long) (min * MINUTES_TO_SECONDS_SCALE * SECONDS_TO_NANOS_SCALE); } public static float nanosToMinutes(long nanos) { return (nanos / SECONDS_TO_NANOS_SCALE / MINUTES_TO_SECONDS_SCALE); } public static float feetToMiles(float feet) { return feet / MILES_TO_FEET_SCALE; } public static float secondsToMinutes(float seconds) { return seconds / MINUTES_TO_SECONDS_SCALE; } public static float metersPerSecondToMinutesPerMile(float metersPerSecond) { if (metersPerSecond == 0.0f) { return 0.0f; } float secondsPerMeter = 1 / metersPerSecond; // seconds per meter return secondsPerMeter * SECONDS_PER_METER_TO_MINUTES_PER_MILE_SCALE; } /** * Prints debugging messages to the console. * * Disabled for non-debug builds. * * @param message - The message to print to the console. */ public static void logDebug(String tag, String message) { if (BuildConfig.DEBUG || DEBUG_LOG) { Log.d(tag, message); } } /** * Builds a file path. * @param rootDirectory Highest directory or file name, if not nested. * @param subDirectories Sub-Directories, or the file name. * @return A string of the file path. */ public static String makeFilePath(String rootDirectory, ArrayList subDirectories) { File file = new File(rootDirectory); for (String subDirectory : subDirectories) { file = new File(file, subDirectory); } return file.toString(); } } ================================================ FILE: app/src/main/res/anim/slide_in_right.xml ================================================ ================================================ FILE: app/src/main/res/anim/slide_out_left.xml ================================================ ================================================ FILE: app/src/main/res/drawable/weapon_charge_progress.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/end_screen.xml ================================================ ================================================ FILE: app/src/main/res/layout/menu_list_item.xml ================================================ ================================================ FILE: app/src/main/res/layout/menu_mission_list.xml ================================================ ================================================ FILE: app/src/main/res/layout/menu_music_selection.xml ================================================