一,知识点。
1,如何自定义View,以及重写它的onDraw方法.
2,Intent实现界面跳转。
3,线程的使用。
4,弹出框框的使用。
二,具体实现代码。
MainLayout文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/container"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:background="@drawable/bg1">
<LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical"android:layout_marginTop="150dp"android:layout_marginLeft="50dp"><Buttonandroid:id="@+id/start_btn"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="开始游戏" /><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/exit_btn"android:text="退出游戏"/></LinearLayout></LinearLayout>
MainActivity文件
package com.example.my.fivegame;import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;public class MainActivity extends AppCompatActivity implements View.OnClickListener{private Button start_btn,exit_btn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);start_btn= (Button) findViewById(R.id.start_btn);exit_btn= (Button) findViewById(R.id.exit_btn);start_btn.setOnClickListener(this);exit_btn.setOnClickListener(this);}@Overrideprotected void onRestart() {super.onRestart();Toast.makeText(this, "其实你无论选择什么都会回到这个界面,想不到吧", Toast.LENGTH_LONG).show();}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.start_btn:{Intent i = new Intent();i.setClass(MainActivity.this, Main2Activity.class);this.startActivity(i);break;}case R.id.exit_btn:{System.exit(0);break;}}}
}
Main2Activity文件
package com.example.my.fivegame;import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;public class Main2Activity extends AppCompatActivity {private int tableWidth;private int tableHeight;private int racketY;private final int RACKET_HEIGHT=30;private final int RACKET_WIDTH=120;private final int BALL_SIZE=16;private int y_Speed=30;private Random rand=new Random();private double xyRate=rand.nextDouble()-0.5;private int x_Speed=(int)(y_Speed*xyRate*2);private int ballX=rand.nextInt(200)-20;private int ballY=700;private int racketX=rand.nextInt(200);public boolean isLose=false;private int nowRow=5;private int nowRol=7;private int[][] mp=new int[nowRow][nowRol];;private int blocks_Wide=RACKET_WIDTH+40;private int blocks_Height=RACKET_HEIGHT*2;private int startX_block=25;private int startY_block=100;private int[] colormp={Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW};private int IntervalX=20;private int IntervalY=30;private int scores=0;private AlertDialog.Builder builder;private List<Main2Activity.mubiao> Anim=new ArrayList<Main2Activity.mubiao>();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//setContentView(R.layout.activity_main2);requestWindowFeature(Window.FEATURE_NO_TITLE);getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);final Main2Activity.GameView gameView=new Main2Activity.GameView(this);setContentView(gameView);gameView.setBackgroundResource(R.drawable.bg4);WindowManager windowManager=getWindowManager();Display display=windowManager.getDefaultDisplay();DisplayMetrics metrics=new DisplayMetrics();display.getMetrics(metrics);tableHeight=metrics.heightPixels;tableWidth=metrics.widthPixels;racketY=tableHeight-300;builder=new AlertDialog.Builder(this);builder.setTitle("提示");builder.setMessage("是否重开一局吗?");builder.setPositiveButton("这次是意外,重开", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();Main2Activity.this.finish();}});builder.setNegativeButton("认怂,就不重开", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();Main2Activity.this.finish();}});Toast.makeText(this, racketY+"与"+tableHeight, Toast.LENGTH_SHORT).show();initmp();final Handler handler=new Handler(){@Overridepublic void handleMessage(Message msg) {if(msg.what==0x123)gameView.invalidate();}};gameView.setOnTouchListener(new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {float x,y;switch (event.getAction()){case MotionEvent.ACTION_DOWN: {x = event.getX();y = event.getY();}case MotionEvent.ACTION_MOVE:{racketX=(int)event.getX();return true;}}return false;}});final Thread thread= new Thread(){boolean IsClick=false;@Overridepublic void run() {for(int i=0;i<Anim.size();i++){int left=Anim.get(i).left;int right=Anim.get(i).right;int top=Anim.get(i).top;int botton=Anim.get(i).botton;if(ballY-5>=top&&ballY-5<=botton&&ballX-5>=left&&ballX+5<=right){scores+=10;if (ballY - 5 >= top && ballY - 5 <= botton) {y_Speed = -y_Speed;Anim.remove(i);break;}if (ballX - 5 >= left && ballX + 5 <= right) {x_Speed = -x_Speed;Anim.remove(i);break;}}}}};final Timer timer=new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {if(ballX<=0||ballX>=tableWidth-BALL_SIZE){x_Speed=-x_Speed;}if(ballY>=racketY-BALL_SIZE&&(ballX<=racketX||ballX>racketX+RACKET_WIDTH)){timer.cancel();isLose=true;}else if(ballY<=0||(ballY>=racketY-BALL_SIZE&&ballX>racketX&&ballX<=racketX+RACKET_WIDTH)){y_Speed=-y_Speed;}ballX+=x_Speed;ballY+=y_Speed;thread.start();handler.sendEmptyMessage(0x123);if(Anim.size()==0){Toast.makeText(Main2Activity.this, "恭喜你成功吃完所有球", Toast.LENGTH_SHORT).show();Main2Activity.this.finish();}}},0,60);}void initmp(){scores=0;for(int i=0;i<nowRow;i++){for(int j=0;j<nowRol;j++){mp[i][j]=rand.nextInt(4);}}int top,botton;top=startY_block;botton=blocks_Height+startY_block;for(int i=0;i<nowRow;i++){if(i!=0) {top += blocks_Height + IntervalY;botton+=blocks_Height + IntervalY;}int left,right;left=startX_block;right=startX_block+blocks_Wide;for(int j=0;j<nowRol;j++){if(j!=0){left+=IntervalX+blocks_Wide;right+=IntervalX+blocks_Wide;}Main2Activity.mubiao one=new Main2Activity.mubiao();one.left=left;one.right=right;one.top=top;one.botton=botton;one.colorid=mp[i][j];Anim.add(one);}}}class GameView extends View{Paint paint=new Paint();public GameView(Context context) {super(context);setFocusable(true);}@Overrideprotected void onDraw(Canvas canvas) {paint.setStyle(Paint.Style.FILL);paint.setAntiAlias(true);for(int i=0;i<Anim.size();i++){int left=Anim.get(i).left;int right=Anim.get(i).right;int top=Anim.get(i).top;int botton=Anim.get(i).botton;paint.setColor(colormp[Anim.get(i).colorid]);canvas.drawRect(left,top,right,botton,paint);}if (isLose) {paint.setColor(Color.RED);paint.setTextSize(40);canvas.drawText("游戏结束,你的最终的分为:"+scores, tableWidth/2-300, tableHeight/2+tableHeight/4, paint);Toast.makeText(Main2Activity.this, "你可以按返回键重新开始游戏", Toast.LENGTH_SHORT).show();builder.create().show();}else{paint.setColor(Color.GREEN);paint.setTextSize(50);canvas.drawText("得分:"+scores, tableWidth/2-100, 50, paint);paint.setColor(Color.BLUE);canvas.drawCircle(ballX,ballY,BALL_SIZE,paint);paint.setColor(Color.BLACK);canvas.drawRect(racketX,racketY,racketX+RACKET_WIDTH,RACKET_HEIGHT+racketY,paint);}super.onDraw(canvas);}}class mubiao{public int left,right,top,botton;public boolean IsClick=false;public int colorid;}
}
实现效果: