用安卓200行代碼開發小遊戲--飛翔的小球

參考視頻:  

https://www.bilibili.com/video/BV16x41177jQ#reply2610860709

https://www.bilibili.com/video/BV1cE411c7uq#reply2612344490

 

界面醜不醜先不管了,能玩就行,就是簡化版的飛行的小鳥

Manifest設置了一個全屏顯示,一個singleTop啓動方式 

 <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen">
        <activity android:name=".MainActivity"
            android:launchMode="singleTop"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

 Mainactivity,因爲要全屏所以要繼承Activity,不懂了看註釋把

package com.example.flyball;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import java.util.Timer;
import java.util.TimerTask;

import static android.content.ContentValues.TAG;

public class MainActivity extends Activity {

    int width; //手機寬
    int height;//手機高
    float ball_size = 16; //小球大小
    float ball_down = 3;//下降速度
    float ball_up = 90;//上升速度
    float ball_X, ball_Y;//小球的x,y座標
    float pillar_height, pillar_2_height, pillar_width = 100, pillar_2_width = 100;//柱子的寬高
    float pillar_X, pillar_2_X, pillar_Y, pillar_2_Y;//柱子的x,y座標
    float pillar_speed = 7;
    int num = 0; //分數
    boolean kill = false;//結束
    MyGameView myGameView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myGameView = new MyGameView(this);
        setContentView(myGameView);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        width = metrics.widthPixels;
        height = metrics.heightPixels;
        init();
    }


    //傳遞消息
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                myGameView.invalidate();
            }
        }
    };

    public void init() {
        kill = false;
        pillar_X = width - pillar_width;
        pillar_Y = 0;
        pillar_2_X = width - pillar_2_width;
        pillar_2_Y = height;
        pillar_width = 100 + (float) (Math.random() * 500 % 401);
        pillar_2_width = pillar_width;
        pillar_height = (float) (Math.random() * (height - 200) % (height - 199)); //height / 2 - 200;
        pillar_2_height = height - pillar_height - 200;
        num = 0;
        pillar_speed =  7;
        ball_down = 3;
        ball_up = 90;
        ball_X = 150;
        ball_Y = height / 2;
        handler.sendEmptyMessage(1);
        //定時器
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                ball_Y += ball_down;
                pillar_X -= pillar_speed;
                pillar_2_X -= pillar_speed;


                //小球碰到邊界去了
                if (ball_Y <= 0 || ball_Y >= height) {
                    kill = true;
                    timer.cancel();
                }

                //小球撞到柱子
                if (ball_X >= pillar_X && ball_X <= pillar_X + pillar_width) {
                    if (ball_Y < pillar_height || ball_Y > pillar_height + 200) {

                        kill = true;
                        timer.cancel();
                    }
                }




                //柱子重繪
                if (pillar_X + pillar_width <= 0) {
                    pillar_X = width;
                    pillar_2_X = width;
                    pillar_width = 100 + (float) (Math.random() * 500 % 401);
                    pillar_2_width = pillar_width;
                    pillar_height = (float) (Math.random() * (height - 200) % (height - 199)); //height / 2 - 200;
                    pillar_2_height = height - pillar_height - 200;
                    num++;
                }


                handler.sendEmptyMessage(1);
            }
        }, 0, 15);

        myGameView.setOnTouchListener(hand);
    }

    //手勢識別
    View.OnTouchListener hand = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    ball_Y -= ball_up;
                    handler.sendEmptyMessage(1);
                    break;
            }
            return true;
        }
    };

    class MyGameView extends View {
        Paint paint = new Paint();
        Bitmap bird;

        public MyGameView(Context context) {
            super(context);
            Bitmap bird;
            bird = BitmapFactory.decodeResource(context.getResources(),R.drawable.fly);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            //設置畫筆屬性
            paint.setStyle(Paint.Style.FILL);
            paint.setAntiAlias(true);
            //Bitmap bitmap = Bitmap.createBitmap(bird, 100, height/2,40,40);

            if (kill) {
                paint.setColor(Color.RED);
                paint.setTextSize(80);
                paint.setTextAlign(Paint.Align.CENTER);
                SharedPreferences preferences = getSharedPreferences("num",MODE_PRIVATE);
                int maxnum = preferences.getInt("num", 0);
                Log.e(TAG, +maxnum +"");
                if (num*10>maxnum) {
                    canvas.drawText("恭喜你創造了新的記錄" + num*10 + "分!!!", width / 2, height / 2, paint);
                    canvas.drawText("最高記錄" + num*10+ "分", width / 2, height / 2+150, paint);
                    SharedPreferences.Editor editor = getSharedPreferences("num", MODE_PRIVATE).edit();
                    editor.putInt("num", num*10);
                    editor.apply();
                   }else {
                    canvas.drawText("遊戲結束,你獲得了" + num*10+ "分,繼續加油!!", width / 2, height / 2, paint);
                    canvas.drawText("最高記錄" + maxnum+ "分", width / 2, height / 2+150, paint);
                }

                this.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            init();
                        }
                        return true;
                    }
                });

            } else {
                paint.setColor(Color.RED);
                paint.setTextSize(80);

                //小球

                //canvas.drawBitmap(bitmap,ball_X,ball_Y,paint);
                canvas.drawCircle(ball_X, ball_Y, ball_size, paint);

                //柱子
                paint.setColor(Color.BLUE);
                canvas.drawRect(pillar_X, pillar_Y, pillar_X + pillar_width, pillar_Y + pillar_height, paint);
                canvas.drawRect(pillar_2_X, pillar_2_Y - pillar_2_height, pillar_2_X + pillar_2_width,
                        pillar_2_Y, paint);

                //計分
                paint.setColor(Color.RED);
                paint.setTextSize(80);
                paint.setTextAlign(Paint.Align.CENTER);
                canvas.drawText(num*10 + "", width / 2, 80, paint);
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章