PageRenderTime 36ms CodeModel.GetById 2ms app.highlight 29ms RepoModel.GetById 1ms app.codeStats 0ms

/androidsays/src/com/google/marvin/androidsays/AndroidSays.java

http://eyes-free.googlecode.com/
Java | 400 lines | 304 code | 71 blank | 25 comment | 20 complexity | d9158a2f85d26cffb6c520ec8dd14c10 MD5 | raw file
  1/*
  2 * Copyright (C) 2008 Google Inc.
  3 * 
  4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5 * use this file except in compliance with the License. You may obtain a copy of
  6 * the License at
  7 * 
  8 * http://www.apache.org/licenses/LICENSE-2.0
  9 * 
 10 * Unless required by applicable law or agreed to in writing, software
 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 13 * License for the specific language governing permissions and limitations under
 14 * the License.
 15 */
 16package com.google.marvin.androidsays;
 17
 18
 19import com.scoreninja.adapter.ScoreNinjaAdapter;
 20
 21import android.app.Activity;
 22import android.app.AlertDialog.Builder;
 23import android.content.DialogInterface;
 24import android.content.DialogInterface.OnClickListener;
 25import android.content.ComponentName;
 26import android.content.Intent;
 27import android.content.SharedPreferences;
 28import android.content.SharedPreferences.Editor;
 29import android.media.AudioManager;
 30import android.net.Uri;
 31import android.os.Bundle;
 32import android.preference.PreferenceManager;
 33import android.view.Menu;
 34import android.view.MenuItem;
 35import android.view.View;
 36import android.widget.Toast;
 37
 38import java.io.File;
 39import java.io.FilenameFilter;
 40import java.util.ArrayList;
 41
 42/**
 43 * mem A memory game for the Android Platform
 44 * 
 45 * @author clchen@google.com (Charles L. Chen)
 46 */
 47public class AndroidSays extends Activity {
 48  protected static final int PREFS_UPDATED = 42;
 49  private static final String THEME_FILE_EXTENSION = ".mem";
 50  private static final String THEMES_BASE_PATH = "/sdcard/mem/themes/";
 51
 52  private GameView gView;
 53
 54  public SfxController sfx;
 55  public int speedPrefDelay;
 56  public int gameMode;
 57  public int sequenceLength;
 58  public boolean halt;
 59
 60  private String[] filenames;
 61  public String themeFilename;
 62  
 63  
 64  private ScoreNinjaAdapter scoreNinjaAdapter;
 65  private String appId = "androidsays";
 66  private String privateKey = "450CA446A7885E7F7B75F19E8F5A39E8";
 67
 68
 69
 70  /** Called when the activity is first created. */
 71  @Override
 72  public void onCreate(Bundle icicle) {
 73    super.onCreate(icicle);
 74    halt = false;
 75    themeFilename = null;
 76    scoreNinjaAdapter = new ScoreNinjaAdapter(this, appId, privateKey);
 77    loadPrefs();
 78    setVolumeControlStream(AudioManager.STREAM_MUSIC);
 79    startApp();
 80  }
 81
 82  private void startApp() {
 83    if (gView != null) {
 84      gView.setVisibility(View.GONE);
 85      gView = null;
 86    }
 87    sfx = new SfxController(this);
 88    gView = new GameView(this);
 89    setContentView(gView);
 90  }
 91
 92
 93
 94  @Override
 95  public boolean onCreateOptionsMenu(Menu menu) {
 96    menu.add(0, R.string.settings, 0, R.string.settings).setIcon(
 97        android.R.drawable.ic_menu_preferences);
 98    menu.add(0, R.string.themes, 0, R.string.themes).setIcon(android.R.drawable.ic_menu_edit);
 99    menu.add(0, R.string.about, 0, R.string.about).setIcon(android.R.drawable.ic_menu_info_details);
100    menu.add(0, R.string.hiscores, 0, R.string.hiscores).setIcon(
101        android.R.drawable.btn_star_big_off);
102    return super.onCreateOptionsMenu(menu);
103  }
104
105  @Override
106  public boolean onOptionsItemSelected(MenuItem item) {
107    Intent intent;
108    switch (item.getItemId()) {
109      case R.string.settings:
110        intent = new Intent(this, PrefsActivity.class);
111        startActivityForResult(intent, PREFS_UPDATED);
112        break;
113      case R.string.themes:
114        displayThemeSelector();
115        break;
116      case R.string.about:
117        displayAbout();
118        break;
119      case R.string.hiscores:
120        displayHiscores();
121        break;
122    }
123    return super.onOptionsItemSelected(item);
124  }
125
126  @Override
127  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
128    if (requestCode == PREFS_UPDATED) {
129      loadPrefs();
130    }
131    super.onActivityResult(requestCode, resultCode, data);
132    scoreNinjaAdapter.onActivityResult(requestCode, resultCode, data);
133  }
134
135  private void loadPrefs() {
136    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
137    // From the game mode setting
138    String modeStr = prefs.getString("game_mode_pref", "1");
139    gameMode = Integer.parseInt(modeStr);
140    String sequenceLengthStr = prefs.getString("sequence_length_pref", "1");
141    sequenceLength = Integer.parseInt(sequenceLengthStr);
142    // From the speed setting
143    String delayStr = prefs.getString("speed_pref", "-1");
144    speedPrefDelay = Integer.parseInt(delayStr);
145    // Load the theme
146    themeFilename = prefs.getString("theme_pref", "");
147  }
148
149  @Override
150  protected void onStop() {
151    halt = true;
152    sfx.stop();
153    super.onStop();
154  }
155
156  @Override
157  protected void onRestart() {
158    reloadGameView();
159    super.onRestart();
160  }
161
162  private void reloadGameView() {
163    halt = false;
164    if (gView != null) {
165      gView.setVisibility(View.GONE);
166      gView = null;
167    }
168    gView = new GameView(this);
169    setContentView(gView);
170  }
171
172  private void displayThemeSelector() {
173    Builder themeFilesDialog = new Builder(this);
174
175    String titleText = "Select a theme";
176    themeFilesDialog.setTitle(titleText);
177
178    File androidSaysDir = new File(THEMES_BASE_PATH);
179    filenames = androidSaysDir.list(new FilenameFilter() {
180      public boolean accept(File dir, String filename) {
181        return filename.endsWith(THEME_FILE_EXTENSION);
182      }
183    });
184
185    // Read the available themes from the SD card
186    ArrayList<String> filenamesArrayList = new ArrayList<String>();
187    filenamesArrayList.add("Default");
188    if (filenames != null) {
189      for (int i = 0; i < filenames.length; i++) {
190        filenamesArrayList.add(filenames[i].substring(0, filenames[i].length()
191            - THEME_FILE_EXTENSION.length()));
192      }
193    } else {
194      filenames = new String[0];
195    }
196    filenames = filenamesArrayList.toArray(filenames);
197
198    themeFilesDialog.setSingleChoiceItems(filenames, -1, new OnClickListener() {
199      public void onClick(DialogInterface dialog, int which) {
200        if (which == 0) {
201          themeFilename = null;
202        } else {
203          themeFilename = THEMES_BASE_PATH + filenames[which] + THEME_FILE_EXTENSION;
204        }
205      }
206    });
207
208    final Activity self = this;
209    themeFilesDialog.setPositiveButton("Apply theme", new OnClickListener() {
210      public void onClick(DialogInterface dialog, int which) {
211        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(self);
212        Editor editor = prefs.edit();
213        editor.putString("theme_pref", themeFilename);
214        editor.commit();
215        reloadGameView();
216        dialog.dismiss();
217      }
218    });
219
220    themeFilesDialog.setNeutralButton("Get new themes", new OnClickListener() {
221      public void onClick(DialogInterface dialog, int which) {
222        if (!new File("/sdcard/").canWrite()) {
223          dialog.dismiss();
224          displayMissingSdCardToast();
225        } else {
226          Intent i = new Intent();
227          ComponentName comp =
228              new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
229          i.setComponent(comp);
230          i.setAction("android.intent.action.VIEW");
231          i.addCategory("android.intent.category.BROWSABLE");
232          Uri uri = Uri.parse("http://groups.google.com/group/mem-game/files");
233          i.setData(uri);
234          self.startActivity(i);
235        }
236      }
237    });
238
239    themeFilesDialog.setNegativeButton("Cancel", new OnClickListener() {
240      public void onClick(DialogInterface dialog, int which) {
241        dialog.dismiss();
242      }
243    });
244
245    themeFilesDialog.show();
246  }
247
248  private void displayMissingSdCardToast() {
249    Toast.makeText(this, "Please insert an SD card before trying to download themes.",
250        Toast.LENGTH_LONG).show();
251  }
252
253  private void displayAbout() {
254    Builder about = new Builder(this);
255
256    String titleText = "mem";
257
258    about.setTitle(titleText);
259    String message = "by Charles L. Chen (clchen@google.com)";
260
261    about.setMessage(message);
262
263    final Activity self = this;
264
265    about.setPositiveButton("Visit website", new OnClickListener() {
266      public void onClick(DialogInterface dialog, int which) {
267        Intent i = new Intent();
268        ComponentName comp =
269            new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
270        i.setComponent(comp);
271        i.setAction("android.intent.action.VIEW");
272        i.addCategory("android.intent.category.BROWSABLE");
273        Uri uri = Uri.parse("http://groups.google.com/group/mem-game");
274        i.setData(uri);
275        self.startActivity(i);
276      }
277    });
278
279    about.setNegativeButton("Close", new OnClickListener() {
280      public void onClick(DialogInterface dialog, int which) {
281
282      }
283    });
284
285    about.show();
286  }
287
288  public void recordScore(int score) {
289    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
290    String modeStr = prefs.getString("game_mode_pref", "1");
291    gameMode = Integer.parseInt(modeStr);
292    String sequenceLengthStr = prefs.getString("sequence_length_pref", "1");
293    String scorePrefStr = "";
294    String subboard = " (" + sequenceLengthStr + ")";
295    if (gameMode == 1) {
296      scorePrefStr = "classic_";
297      subboard = "Classic Mode" + subboard;
298    } else {
299      scorePrefStr = "challenge_";
300      subboard = "Challenge Mode" + subboard;
301    }
302    scorePrefStr = scorePrefStr + sequenceLengthStr;
303
304    int prevHiScore = Integer.parseInt(prefs.getString(scorePrefStr, "0"));
305    int diff = score - prevHiScore;
306    if (diff > 0) {
307      Editor editor = prefs.edit();
308      editor.putString(scorePrefStr, Integer.toString(score));
309      editor.commit();
310
311      Toast.makeText(this, "You beat your old record by " + diff + "!", Toast.LENGTH_LONG).show();
312    }
313    
314    scoreNinjaAdapter.show(score, "Top Scores for " + subboard, subboard);
315  }
316
317
318  private void displayHiscores() {
319    Builder hiscores = new Builder(this);
320
321    String titleText = "High Scores";
322
323    hiscores.setTitle(titleText);
324
325    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
326
327    String message = "Classic mode   (1):  " + prefs.getString("classic_1", "0") + "\n";
328    message = message + "Classic mode   (5):  " + prefs.getString("classic_5", "0") + "\n";
329    message = message + "Classic mode (10):  " + prefs.getString("classic_10", "0") + "\n";
330    message = message + "Classic mode (20):  " + prefs.getString("classic_20", "0") + "\n";
331    message = message + "Classic mode (30):  " + prefs.getString("classic_30", "0") + "\n" + "\n";
332    message = message + "Challenge mode   (1):  " + prefs.getString("challenge_1", "0") + "\n";
333    message = message + "Challenge mode   (5):  " + prefs.getString("challenge_5", "0") + "\n";
334    message = message + "Challenge mode (10):  " + prefs.getString("challenge_10", "0") + "\n";
335    message = message + "Challenge mode (20):  " + prefs.getString("challenge_20", "0") + "\n";
336    message = message + "Challenge mode (30):  " + prefs.getString("challenge_30", "0");
337
338
339    hiscores.setMessage(message);
340
341    hiscores.setPositiveButton("Erase high scores", new OnClickListener() {
342      public void onClick(DialogInterface dialog, int which) {
343        displayScoreResetConfirmation();
344        dialog.dismiss();
345      }
346    });
347
348    hiscores.setNegativeButton("Close", new OnClickListener() {
349      public void onClick(DialogInterface dialog, int which) {
350      }
351    });
352
353    hiscores.show();
354  }
355
356
357  private void displayScoreResetConfirmation() {
358    Builder confirmation = new Builder(this);
359
360    String titleText = "Erase high scores?";
361
362    confirmation.setTitle(titleText);
363
364    String message = "Are you sure you want to erase the high scores?";
365
366    confirmation.setMessage(message);
367
368    final Activity self = this;
369
370    confirmation.setPositiveButton("Yes", new OnClickListener() {
371      public void onClick(DialogInterface dialog, int which) {
372        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(self);
373        Editor editor = prefs.edit();
374        editor.putString("classic_1", "0");
375        editor.putString("classic_5", "0");
376        editor.putString("classic_10", "0");
377        editor.putString("classic_20", "0");
378        editor.putString("classic_30", "0");
379        editor.putString("challenge_1", "0");
380        editor.putString("challenge_5", "0");
381        editor.putString("challenge_10", "0");
382        editor.putString("challenge_20", "0");
383        editor.putString("challenge_30", "0");
384        editor.commit();
385        dialog.dismiss();
386      }
387    });
388
389    confirmation.setNegativeButton("No", new OnClickListener() {
390      public void onClick(DialogInterface dialog, int which) {
391      }
392    });
393
394    confirmation.show();
395  }
396  
397
398  
399
400}