Huong Dan Tao Vong Lap Game Don Gian

Embed Size (px)

Citation preview

Cho cc bn. Ngy cng c nhiu ngi thch lp trnh game hn. Cc bn mi bt u thng c cu hi Mnh nn bt u t u nh?.. Cu hi cng kh tr li. Hm nay mnh xin hng dn to 1 vng lp game n gin (Android). 1. To ra 1 d n.

Chn File->new>Android Project

t tn ty V d: VIDU

Chn next

Chn android 2.3.3 ri chn next

Package: vidu.vidu Chn finish

Kt qu l c 1 file VIDUActivity

2. Gi c project ta thm cc thnh phn khc. - To 1 lp l VongLap.java - Sau copy ni dung sau vo lp ny.package vidu.vidu; import java.util.Timer; import java.util.TimerTask; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.AttributeSet; import android.widget.LinearLayout; /** * Base class for all games. Extends {@link LinearLayout} and uses a * {@link TimerTask} to invalidate the view * * @author V. Silva * */ public abstract class VongLap extends LinearLayout { // App context private Context mContex; // Update timer used to invalidate the view private Timer mUpdateTimer; // Timer period private long mPeriod = 1000; /** *C * * @param context */ public VongLap(Context context) { super(context); mContex = context; } public VongLap(Context context, AttributeSet attrs) { super(context, attrs); mContex = context; } /** * Fires on layout */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); try { // Init game initialize(); /** * start update task. Which will fire onDraw in the future */ startUpdateTimer(); } catch (Exception e) { // bug

e.printStackTrace(); } }

/** * Set the update period * * @param period */ public void setUpdatePeriod(long period) { mPeriod = period; } /** * A timer is used to move the sprite around */ protected void startUpdateTimer() { mUpdateTimer = new Timer(); mUpdateTimer.schedule(new UpdateTask(), 0, mPeriod); } protected void stopUpdateTimer() { if (mUpdateTimer != null) { mUpdateTimer.cancel(); } } public Context getContex() { return mContex; } /** * Load an image * * @param id * @return */ protected Bitmap getImage(int id) { return BitmapFactory.decodeResource(mContex.getResources(), id); } /** * Overload this to update the sprites on the game */ abstract protected void updatePhysics(); /** * Overload to initialize the game */ abstract protected void initialize(); abstract protected boolean gameOver(); abstract protected long getScore(); /** * Canvas update task * * @author vsilva * */

private class UpdateTask extends TimerTask { @Override public void run() { updatePhysics(); /** * Cause an invalidate to happen on a subsequent cycle through the * event loop. Use this to invalidate the View from a non-UI thread. * onDraw will be called sometime in the future. */ postInvalidate();

} }

/** * Halt game. Stops the update task. Called by a parent activity to halt * */ public void halt() { stopUpdateTimer(); } /** * Resume Game */ public void resume() { initialize(); startUpdateTimer(); }

}

Tip theo: Vi lp VIDUActivity ta thm don code sau.package vidu.vidu; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; public class VIDUActivity extends Activity { private View view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // full man hinh requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); LayoutInflater factory = LayoutInflater.from(this); // Set game layout view = factory.inflate(R.layout.main, null); setContentView(view); // Enable view key events

view.setFocusable(true); view.setFocusableInTouchMode(true); } @Override protected void onStop() { super.onStop(); ((VongLap) view).halt(); } @Override protected void onPause() { super.onPause(); onStop(); } @Override protected void onRestart() { super.onRestart(); ((VongLap) view).resume(); }

}

3. Gi chng ta s to ra 1 lp khc. To lp tn l Game package vidu.vidu; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.MotionEvent; public class Game extends VongLap { // ================================================================= ===== // Game name public static final String NAME = "VIDU"; // Thi gian lm ti mn hnh l 40 mili giy private static final long UPDATE_DELAY = 40; int width = getWidth(); int height = getHeight(); boolean runGame = false; // ---------------------------------------------------------------------public Game(Context context) { super(context); super.setUpdatePeriod(UPDATE_DELAY); } public Game(Context context, AttributeSet attrs) { super(context, attrs); super.setUpdatePeriod(UPDATE_DELAY); } @Override protected void onDraw(Canvas canvas) { super.dispatchDraw(canvas); paint(canvas); } // ---------------------------------------------------------------------// ---------------------------PHUONG THUC KHOI TAO----------------------public void initialize() { GameStart();// bat dau game } // ---------------------------------------------------------------------// ------------------------------VE THANH PHAN GAME---------------------public void paint(Canvas c) { if (runGame) { //V ci g } } // ---------------------------------------------------------------------// --------------------SU KIEN CHAM MAN HINH----------------------------@Override public boolean onTouchEvent(MotionEvent event) { return true; } // ---------------------------------------------------------------------// -------------------------SU KIEN KHI NHAN PHIM------------------------

@Override public boolean onKeyUp(int keyCode, KeyEvent event) { return true; } // ---------------------------------------------------------------------// --------------------------SU KIEN NHA PHIM---------------------------@Override public boolean onKeyDown(int keyCode, KeyEvent event) { return true; } // ================================================================= ===== // Game Start public void GameStart() { runGame = true; } // Game Over public void GameOver() { runGame = false; } @Override protected void updatePhysics() { if (runGame) { } } @Override protected boolean gameOver() { return runGame; } @Override protected long getScore() { return 0; }

}

Thay i ni dung file main.xml thnh:

4. Hin th dng helloworld Ti lp Game ta khai bo thm bin Paint p; Sau thm vo phng thc initialize() nh sau.public void initialize() { //Khoi tao bien p p = new Paint(); //dat mau chu l mau trang p.setColor(Color.WHITE); //t kch thc ch l 25px p.setTextSize(25); GameStart();// bat dau game } v c dng ch th ta thm vo phng thc sau public void paint(Canvas c) { if (runGame) { //V ci g //v text c.drawText("HelloWorld", 100, 100, p); } }

Gi th chy v nhn kt qu thi.

Bi sau mnh s hng dn cc bn cch load nh v v nh.

Bi 2: Nh bi trc mnh gii thiu. Hm nay mnh s hng dn cc bn load nh v v nh. load c nh ta thm cc thnh phn nh sau. 1. Khai bo thm 2 bin na. Bitmap anh; public static Context mcontext; bin anh dng lu bc nh cn v. bin mcontext dng load d liu. 2. Ti 2 phng thc khi dng ta thm vo 1 dng nh sau: mcontext = context; 3. Ti phng thc initialize() ta thm on code sau load nh. anh = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.android); y bc nh chng ta v c tn l android. Bc nh ny t trong th mc res\drawable\android.jpg 4. nh load song, gi ta s v nh ln mn hnh.Thm cu lnh sao vo phng thc paint. c.drawBitmap(anh, 50, 100, p); // v bc nh ta x=50, y=100; nh kt qu: