前面兩篇“實現篇”已經將程式後台架構基本實現了,今天將涉及程式的activity類,在這個類中,為了有一個比較好的視覺效果,將介紹一些android中動畫效果,依靠animation來實現,以及簡單介紹android中自訂dialog的實現;首先看一下遊戲介面運行時的(程式中圖片使用了網上的網友的,僅當學習之用):
遊戲運行時介面 用於顯示遊戲結果的自訂dialog顯示
先看看用於顯示程式的activity類中的代碼(這裡主要是一些調用等,實現的邏輯在前面兩篇文章中已經包含了)
package nate.llk;//包得匯入略去public class GameActivity extends Activity implements OnToolsChangeListener,OnTimerListener,OnStateListener{private ImageButton img_startPlay;private ImageView img_title;private ProgressBar progress;private MyDialog dialog;//visibility at first is "gone"private ImageView clock;private GameView gameView = null;private ImageButton img_tip;private ImageButton img_refresh;private TextView text_refreshNum;private TextView text_tipNum;//兩個協助按鍵的特效private Animation anim = null;private Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {switch(msg.what){case 0:dialog = new MyDialog(GameActivity.this,gameView,"完成!",gameView.getTotalTime() - progress.getProgress() + 1);dialog.show();break;case 1:dialog = new MyDialog(GameActivity.this,gameView,"失敗!",gameView.getTotalTime() - progress.getProgress() + 1);dialog.show();}}}; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game_view); anim = AnimationUtils.loadAnimation(this, R.anim.shake); findView(); startView(); img_startPlay.setOnClickListener(new BtnClickListener()); gameView.setOnTimerListener(this); gameView.setOnStateChangeListener(this); gameView.setOnToolsChangedListener(this); img_refresh.setOnClickListener(new BtnClickListener()); img_tip.setOnClickListener(new BtnClickListener()); }//end of the OnCreate method! /** * 尋找對應資原始檔控制 */ public void findView(){ clock = (ImageView)this.findViewById(R.id.clock); progress = (ProgressBar)this.findViewById(R.id.timer); img_title = (ImageView)this.findViewById(R.id.title_img); img_startPlay = (ImageButton)this.findViewById(R.id.play_btn); img_tip = (ImageButton)this.findViewById(R.id.tip_btn); img_refresh = (ImageButton)this.findViewById(R.id.refresh_btn); gameView = (GameView)this.findViewById(R.id.game_view); text_refreshNum = (TextView)this.findViewById(R.id.text_refresh_num); text_tipNum = (TextView)this.findViewById(R.id.text_tip_num); } /** * 程式開啟介面顯示 */ public void startView(){ Animation scale = AnimationUtils.loadAnimation(this,R.anim.scale_anim); img_title.startAnimation(scale); img_startPlay.startAnimation(scale); } /** * 遊戲運行時介面顯示,即連連看的布局 */ public void playingView(){ Animation scaleOut = AnimationUtils.loadAnimation(this, R.anim.scale_anim_out); img_title.startAnimation(scaleOut); img_startPlay.startAnimation(scaleOut); img_title.setVisibility(View.GONE); img_startPlay.setVisibility(View.GONE); clock.setVisibility(View.VISIBLE); progress.setMax(gameView.getTotalTime()); progress.setProgress(gameView.getTotalTime()); progress.setVisibility(View.VISIBLE); gameView.setVisibility(View.VISIBLE); img_tip.setVisibility(View.VISIBLE); img_refresh.setVisibility(View.VISIBLE); text_tipNum.setVisibility(View.VISIBLE); text_refreshNum.setVisibility(View.VISIBLE); Animation animIn = AnimationUtils.loadAnimation(this, R.anim.trans_in); gameView.startAnimation(animIn); img_tip.startAnimation(animIn); img_refresh.startAnimation(animIn); text_tipNum.startAnimation(animIn); text_refreshNum.startAnimation(animIn); //player.pause();gameView.startPlay();toast(); } /** * 一個處理開始遊戲,重新整理,協助三個按鈕的listener的類 * @author HelloPe || NatePan * */ class BtnClickListener implements OnClickListener{@Overridepublic void onClick(View v) {switch(v.getId()){case R.id.play_btn:playingView();break;case R.id.refresh_btn:img_refresh.startAnimation(anim);gameView.refreshChange();gameView.invalidate();break;case R.id.tip_btn:img_tip.startAnimation(anim);gameView.autoHelp();break;}} }@Overridepublic void onRefreshChanged(int count) {text_refreshNum.setText(""+gameView.getRefreshNum());}@Overridepublic void onTipChanged(int count) {text_tipNum.setText("" + gameView.getTipNum());}@Overridepublic void onTimer(int leftTime) {progress.setProgress(leftTime);}/** *用來控制音樂的播放 */@Overridepublic void OnStateChanged(int StateMode) {switch(StateMode){case GameView.WIN:handler.sendEmptyMessage(0);break;case GameView.LOSE:handler.sendEmptyMessage(1);break;case GameView.PAUSE://player.stop(); //gameView.player.stop(); gameView.stopTimer();break;case GameView.QUIT://player.release(); //gameView.player.release(); gameView.stopTimer(); break;}}public void quit(){this.finish();}/** * 用於提醒遊戲開始,提醒總時間 */public void toast(){Toast.makeText(this, "遊戲已經開始!總時間: " + gameView.getTotalTime() + "s", Toast.LENGTH_LONG).show();} @Override protected void onPause() { super.onPause(); gameView.setMode(GameView.PAUSE); } @Overrideprotected void onDestroy() { super.onDestroy(); gameView.setMode(GameView.QUIT);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {menu.add(Menu.NONE, 1, Menu.NONE,"Replay").setIcon(R.drawable.buttons_replay);menu.add(Menu.NONE, 2, Menu.NONE, "Pause").setIcon(R.drawable.pause);menu.add(Menu.NONE, 3, Menu.NONE,"SoundOn").setIcon(R.drawable.volume);return super.onCreateOptionsMenu(menu);}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch(item.getItemId()){case 1:gameView.setTotalTime(100);progress.setMax(100);gameView.startPlay();break;case 2:gameView.stopTimer();if(item.getTitle().equals("Pause")){item.setTitle("Continue");item.setIcon(R.drawable.play);}else if(item.getTitle().equals("Continue")){item.setTitle("Pause");item.setIcon(R.drawable.pause);}AlertDialog.Builder dialog = new AlertDialog.Builder(this);dialog.setIcon(R.drawable.icon);dialog.setTitle("繼續");dialog.setMessage("繼續遊戲?");dialog.setPositiveButton("繼續", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {gameView.setContinue();}}).setNeutralButton("重玩", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {gameView.startPlay();}}).setNegativeButton("退出", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Intent startMain = new Intent(Intent.ACTION_MAIN); startMain.addCategory(Intent.CATEGORY_HOME); startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(startMain); System.exit(0); }});dialog.show();break;case 3:///////////////////////////if(item.getTitle().equals("Mute")){item.setTitle("SoundOn");item.setIcon(R.drawable.volume);}else if(item.getTitle().equals("SoundOn")){item.setTitle("Mute");item.setIcon(R.drawable.mute);}break;}return super.onOptionsItemSelected(item);}/** * 監聽後退按鈕,以防止誤按,按下back按鈕後,程式應當處於暫停狀態 */@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if(keyCode == KeyEvent.KEYCODE_BACK){AlertDialog.Builder dialog= new AlertDialog.Builder(GameActivity.this).setTitle("離開遊戲").setMessage("確定離開遊戲?").setPositiveButton("是",new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which) {Intent startMain = new Intent(Intent.ACTION_MAIN); startMain.addCategory(Intent.CATEGORY_HOME); startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(startMain); System.exit(0); }}).setNegativeButton("否", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(GameActivity.this, "重新開始了遊戲", Toast.LENGTH_LONG).show();gameView.startPlay();}});dialog.setIcon(R.drawable.icon);dialog.show();}return super.onKeyDown(keyCode, event);} }
在此類中,如上次我們所說的,我們實現了之前定義的三個介面,引用了GameView類(在activity的布局檔案中使用到),在activity布局檔案中如下使用:
<nate.llk.view.GameView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/game_view" android:visibility="gone" android:layout_below="@id/timer" />
同樣對於我們自訂的dialog,跟自訂的GameView(繼承自View)是一樣的。MyDialog類繼承自Dialog類,實現了OnClickListener的OnClick方法,使用一個布局檔案,將自訂的dialog布局。布局檔案很簡單,MyDialog類如下:
package nate.llk;//匯入包略去
public class MyDialog extends Dialog implements OnClickListener{private GameView gameview;private Context context;public MyDialog(Context context, GameView gameview, String msg, int time) {super(context,R.style.dialog);this.gameview = gameview;this.context = context;this.setContentView(R.layout.dialog_view);TextView text_msg = (TextView) findViewById(R.id.text_message);TextView text_time = (TextView) findViewById(R.id.text_time);ImageButton btn_menu = (ImageButton) findViewById(R.id.menu_imgbtn);ImageButton btn_next = (ImageButton) findViewById(R.id.next_imgbtn);ImageButton btn_replay = (ImageButton) findViewById(R.id.replay_imgbtn);text_msg.setText(msg);text_time.setText(text_time.getText().toString().replace("$", String.valueOf(time)));btn_menu.setOnClickListener(this);btn_next.setOnClickListener(this);btn_replay.setOnClickListener(this);this.setCancelable(false);}@Overridepublic void onClick(View v) {this.dismiss();switch(v.getId()){case R.id.menu_imgbtn:Dialog dialog = new AlertDialog.Builder(context) .setIcon(R.drawable.buttons_bg20) .setTitle(R.string.quit) .setMessage(R.string.sure_quit) .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ((GameActivity)context).quit(); } }) .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { gameview.startPlay(); } }) .create();dialog.show();break;case R.id.replay_imgbtn:gameview.startPlay();break;case R.id.next_imgbtn:gameview.startNextPlay();break;}}@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if(keyCode == KeyEvent.KEYCODE_BACK){this.dismiss();}return super.onKeyDown(keyCode, event);}}
上面代碼簡單,不過還是實現了較好的效果。
在android中使用animation的動畫包含四種,Tween animation的使用也能夠使程式看起來效果好點:
在anim檔案下:
實現當點擊程式中兩個工具按鈕時,工具按鈕出現抖動的效果:
<?xml version="1.0" encoding="utf-8"?><translate xmlns:android="http://schemas.android.com/apk/res/android" android:fromXDelta="0" android:toXDelta="10" android:duration="1000" android:interpolator="@anim/cycle" />
<?xml version="1.0" encoding="utf-8"?><cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android" android:cycles="7" /><!--用於控制上面顫動的次數-->
用於控制歡迎介面的表徵圖逐漸層大的出場效果:
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"><scale android:interpolator="@android:anim/accelerate_decelerate_interpolator" android:fromXScale="0.0" android:toXScale="1.0" android:fromYScale="0.0" android:toYScale="1.0" android:pivotX="50%" android:pivotY="50%" android:fillAfter="true" android:duration="1600" /></set>
當然放大效果只是改一下android:fromXScale="1.0" 與 android:toXScale="0.0"即可;
至於透明效果,用於將GameView中的內容從透明慢慢展示出來:
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"><alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="1000" /></set>
而在activity中對於以上資源的使用上面activity類中已經給出,先載入,然後調用imageView或者其他View的startAnimation方法即可;
對於遊戲中音效的播放方法比較簡單,主要是在不同的狀態播放不同的聲音比較繁瑣,android中有兩種播放音效的方法:一種是SoundPool,一種是MediaPlayer。SoundPool適合短促音樂,但是反應速度要求比較高的情況;MediaPlayer則是是相反。使用步驟如:
// 初始化soundPool 對象,第一個參數是允許有多少個聲音流同時播放,第2個參數是聲音類型,第三個參數是聲音的品質soundPool = new SoundPool(25, AudioManager.STREAM_MUSIC, 100);//SoudPool的引用soundPool.load(context, raw, 1);//調用load函數載入音樂資源//之後調用play函數即可播放參數中相應的音樂資源
本程式算是完成了,向網友們學習了不少,畢竟是很多人都做過的小項目。記錄下來,希望高手路過別噴~
while(success != try());