Android 微信搖骰子
阿新 • • 發佈:2019-01-23
過年怎麼可以不玩紅包娛樂一下呢,微信裡的搖骰子大小和石頭剪刀布就是不錯的遊戲方式。
使用Java的Random函式很容易實現,以骰子為例:
1.骰子搖動的動畫,使用animation-list幀動畫實現
2.生成1~6的隨機數,1 + new Random().nextInt(6)
以下是程式碼實現,文末提供圖片資源下載:
package com.zms.dicedemo; import java.util.Random; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity { private ImageView imageDice; private Button btnGo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initialLayout(); } private void initialLayout() { imageDice = (ImageView) findViewById(R.id.imageDice); btnGo = (Button) findViewById(R.id.btnGo); btnGo.setOnClickListener(new MyOnClickListener()); } class MyOnClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnGo: imageDice.setImageDrawable(getResources().getDrawable( R.drawable.anim_dice)); new Thread(new DiceThread()).start(); break; default: break; } } } public class DiceThread implements Runnable { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } Message messageDice = new Message(); messageDice.what = 1; diceHandler.sendMessage(messageDice); } } private void resetDiceImage() { int randomInt = 1 + new Random().nextInt(6); // 1~6 Toast.makeText(MainActivity.this, getChineseByNumber(randomInt), Toast.LENGTH_SHORT).show(); imageDice.setImageDrawable(getResources().getDrawable( getResources().getIdentifier("dice_" + randomInt, "drawable", getPackageName()))); } private String getChineseByNumber(int number) { switch (number) { case 1: return "一點小"; case 2: return "二點小"; case 3: return "三點小"; case 4: return "四點大"; case 5: return "五點大"; case 6: return "六點大"; default: return ""; } } final Handler diceHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 1: resetDiceImage(); break; default: break; } } }; }
Random生成的雖然是偽隨機數,但是在娛樂對安全性要求不高,還是可以使用的。
實現方式比較簡單,以下是工程下載連結: