It was a man who went down Layer 4 [Layer 4] -- Crazy greedy snake (1). Suddenly there was the fourth layer of the day.

Source: Internet
Author: User

It was a man who went down Layer 4 [Layer 4] -- Crazy greedy snake (1). Suddenly there was the fourth layer of the day.

Snake is a classic game. These classic games have added a lot of fun to our childhood. Today, we start to implement a Snake Game On Android devices step by step, I am also writing this game for the first time. I may make mistakes or take a detour, but I hope to have a good result. Next, let's explore the stone development step by step.

1. Create a project
Ii. Custom View (snake Interface)
package com.example.crazysnake;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.RectF;import android.util.AttributeSet;import android.view.View;public class MySnake extends View {private Paint paint;private RectF rect;public MySnake(Context context, AttributeSet attrs) {super(context, attrs);paint = new Paint();rect = new RectF();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);rect.set(50, 50, 90, 90);paint.setColor(Color.RED);canvas.drawRect(rect, paint);}}
Layout File
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" ><com.example.crazysnake.MySnake     android:layout_width="match_parent"    android:layout_height="match_parent"/></LinearLayout>
Running Effect: we drew a small square on the interface, which is the basis for us to complete the snake (as important as building bricks) 3. Draw a colored snake and create a square object first
package com.example.crazysnake;public class Box {private int x;private int y;public Box(int x, int y) {super();this.x = x;this.y = y;}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}}
Draw a line of squares
package com.example.crazysnake;import java.util.ArrayList;import java.util.List;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.RectF;import android.util.AttributeSet;import android.view.View;public class MySnake extends View {private Paint paint;private RectF rect;private int boxSize = 30;private List<Box> boxs = new ArrayList<Box>();private static final int[] colors = {Color.RED,Color.BLUE, Color.GREEN,Color.YELLOW};public MySnake(Context context, AttributeSet attrs) {super(context, attrs);paint = new Paint();rect = new RectF();initData();}private void initData(){Box box;for(int i=0; i<10; i++){box = new Box(i*boxSize, 0);boxs.add(box);}}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);for(int i=0; i<boxs.size(); i++){paint.setColor(colors[i % colors.length]);rect.set(boxs.get(i).getX(), boxs.get(i).getY(), boxs.get(i).getX() + boxSize, boxSize);canvas.drawRect(rect, paint);}}}
4. Let the color snake move and rewrite the onTouchEvent Method
@Overridepublic boolean onTouchEvent(MotionEvent event) {System.out.println("onTouch");switch (event.getAction()) {case MotionEvent.ACTION_DOWN:mDownX = event.getX();mDownY = event.getY();break;case MotionEvent.ACTION_UP:float disX = event.getX() - mDownX;float disY = event.getY() - mDownY;System.out.println("disX = " + disX);System.out.println("dixY = " + disY);if(Math.abs(disX) > Math.abs(disY)){if(disX > 0){System.out.println("right");move(Derectory.RIGHT);}else{move(Derectory.LEFT);}}else{if(disY > 0){}else{}}break;}return true;}
Move method to move in the direction
private void move(Derectory derectory){Box box;int bs = 0;switch (derectory) {case LEFT:case TOP:bs = - boxSize;break;case RIGHT:case BOTTOM:bs = boxSize;break;}if(derectory == Derectory.LEFT || derectory == Derectory.RIGHT){for(int i=0; i<boxs.size(); i++){box = boxs.get(i);box.setX(box.getX() + bs);}}else{for(int i=0; i<boxs.size(); i++){box = boxs.get(i);box.setY(box.getY() + bs);}}invalidate();}
In the above Code, we do not control the boundary. We need to add code to judge the boundary condition. 5. Let the snake run automatically. Let's control it to start a thread and let the snake run automatically.
private class SnakeThread extends Thread{private boolean stoped = false;@Overridepublic void run() {while(!stoped){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}move();postInvalidate();}}}
The Code is as follows:
package com.example.crazysnake;import java.util.ArrayList;import java.util.List;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.RectF;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;public class MySnake extends View {private Paint paint;private RectF rect;private int boxSize = 30;private SnakeThread snakeThread;private List<Box> boxs = new ArrayList<Box>();private static final int[] colors = {Color.RED,Color.BLUE, Color.GREEN,Color.YELLOW};private enum Derectory{LEFT,RIGHT,TOP,BOTTOM;}private Derectory currentDerect = Derectory.RIGHT;public MySnake(Context context, AttributeSet attrs) {super(context, attrs);paint = new Paint();rect = new RectF();initData();startThread();}public void startThread(){if(snakeThread == null){snakeThread = new SnakeThread();snakeThread.start();}}private void initData(){Box box;for(int i=0; i<10; i++){box = new Box(i*boxSize, 0);boxs.add(box);}}private float mDownX;private float mDownY;@Overridepublic boolean onTouchEvent(MotionEvent event) {System.out.println("onTouch");switch (event.getAction()) {case MotionEvent.ACTION_DOWN:mDownX = event.getX();mDownY = event.getY();break;case MotionEvent.ACTION_UP:float disX = event.getX() - mDownX;float disY = event.getY() - mDownY;System.out.println("disX = " + disX);System.out.println("dixY = " + disY);if(Math.abs(disX) > Math.abs(disY)){if(disX > 0){currentDerect = Derectory.RIGHT;}else{currentDerect = Derectory.LEFT;}}else{if(disY > 0){currentDerect = Derectory.BOTTOM;}else{currentDerect = Derectory.TOP;}}break;}return true;}private class SnakeThread extends Thread{private boolean stoped = false;@Overridepublic void run() {while(!stoped){try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}move();postInvalidate();}}}private void move(){Box box;if(boxs.get(0).getX() - boxSize < 0) {currentDerect = Derectory.RIGHT;}if(boxs.get(boxs.size() - 1).getX() + 2 * boxSize > getWidth()){currentDerect = Derectory.LEFT;}switch (currentDerect) {case LEFT:for(int i=0; i<boxs.size(); i++){box = boxs.get(i);box.setX(box.getX() - boxSize);}break;case RIGHT:for(int i=0; i<boxs.size(); i++){box = boxs.get(i);box.setX(box.getX() + boxSize);}break;case TOP:break;case BOTTOM:break;}}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);for(int i=0; i<boxs.size(); i++){paint.setColor(colors[i % colors.length]);rect.set(boxs.get(i).getX(), boxs.get(i).getY(), boxs.get(i).getX() + boxSize, boxSize);canvas.drawRect(rect, paint);}}}

Come here today, and continue tomorrow... ^-^


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.