android贪吃蛇完整代码

以下是我花了两天时间由一个简单的画矩形的例子改造而来的,还没有来得急测试就贴上了,追求完美的朋友还需要认真玩下啦.我就去做其他例子了.

游戏是由重写view类完成的,所以没有布局文件,这和官方的实例不一样,是直接画图,所以也没有图片,你只要建立个应用复制下代码应该没有问题啦.

看图:文字和方块是不采用屏幕比例的大小输出,所以从手机上要的图很不好看了,有空自己改改.

android贪吃蛇完整代码_第1张图片android贪吃蛇完整代码_第2张图片

主代码:完成游戏控制

package org.mytest.snake;

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnKeyListener;

public class mainActivity extends Activity
{
	// 屏幕宽度
	private int width;
	// 屏幕高度
	private int height;
	SnakeView snake;
	private int direction; 
	Boolean start=false;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		// 去掉窗口标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 全屏显示
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
								WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// 获取窗口管理器
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		DisplayMetrics metrics = new DisplayMetrics();
		display.getMetrics(metrics);
		// 获得屏幕宽和高
		width = metrics.widthPixels;
		height = metrics.heightPixels;
		snake=new SnakeView(this,width,height);
		direction=snake.direction;
		setContentView(snake);
		startgame();
		
	}
	
	@SuppressLint("HandlerLeak")
	private void startgame() {
		// TODO 自动生成的方法存根
		
		final Handler handler = new Handler()
		{
			@SuppressLint("HandlerLeak")
			public void handleMessage(Message msg)
			{
				if (msg.what == 0x123)
				{
					snake.invalidate();
				}
			}
		};
		snake.setOnClickListener(new OnClickListener()
	    {
			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				start=true;
				snake.pause=false;
				snake.firstStart=false;
				if(snake.isOver)
				{
					snake.replay();
				}
				
			}
	    	
	    });
		snake.setOnKeyListener(new OnKeyListener() 
		{
			@Override
			public boolean onKey(View source, int keyCode, KeyEvent event)
			{
				if(start){
					// 获取由哪个键触发的事件
					switch (event.getKeyCode())
					{
						// 左移
						case KeyEvent.KEYCODE_A:
							direction=snake.LEFT;
							break;
						// 右移
						case KeyEvent.KEYCODE_D:
							direction=snake.RIGHT;
							break;
							// 上移
						case KeyEvent.KEYCODE_W:
							direction=snake.TOP;
							break;
							// 下移
						case KeyEvent.KEYCODE_S:
							direction=snake.BOTTOM;
							break;
					}
				}
				return false;
			}
		});
		snake.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (start) 
                {            
                    float x = event.getX() / v.getWidth();
                    float y = event.getY() / v.getHeight();
                    direction = (x > y) ?((x>1-y)?snake.RIGHT:snake.TOP):((x>1-y)?snake.BOTTOM:snake.LEFT);                 
                } 
                return false;
            }
        });
		final Timer timer = new Timer();
		timer.schedule(new TimerTask()
			{

				@Override
				public void run()
				{
					if(start&&!snake.isOver)
					{
						snake.snakeMove(direction);
						// 发送消息,通知系统重绘组件
						handler.sendEmptyMessage(0x123);
						if(snake.pause)
						{
							start=false;
						}
					}
					else
					{
						start=false;
					}
				}
			}, 0, 500);
	}
	@Override
    protected void onPause() {
        super.onPause();
        snake.pause=true;
    }

}
重写view类:完成图形的绘画

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.view.View;


class SnakeView extends View
{
	int stepx,stepy;
	Chip chip=new Chip(0,0,0);
	Paint paint=new Paint();
	Random rand = new Random();
	List snake=new ArrayList();
	List food=new ArrayList();
	public final int TOP=0;
	public final int BOTTOM=1;
	public final int LEFT=2;
	public final int RIGHT=3;
	int direction;
	Boolean find;
	Boolean firstStart=true;
	Boolean pause=false;
	Boolean isOver=false;
	int code=0;
	public SnakeView(Context context)
	{
		super(context);
		setFocusable(true);
	}
	public SnakeView(Context context,int width,int height)
	{
		super(context);
		setFocusable(true);
		stepx=width/chip.LENGTH;
		stepy=height/chip.LENGTH;
		direction=BOTTOM;
		setSnake();   
		foodPlace(2);
	}
	@SuppressLint("DrawAllocation")
	public void onDraw(Canvas canvas)
	{

		canvas.drawRGB(0, 0xbf,0xff);
		
		paint.setColor(Color.rgb(0, 0, 0));
		canvas.drawRect(chip.LENGTH,chip.LENGTH, stepx*chip.LENGTH-chip.LENGTH,
				stepy*chip.LENGTH-chip.LENGTH, paint);
		paint.setColor(Color.rgb(36, 64, 0x8B));
		Path p1=new Path();
		p1.moveTo(chip.LENGTH, chip.LENGTH);
		p1.lineTo(stepx*chip.LENGTH/2, stepy*chip.LENGTH/2);
		p1.lineTo(chip.LENGTH, stepy*chip.LENGTH-chip.LENGTH);
		p1.close();
		canvas.drawPath(p1, paint);
		p1.moveTo(stepx*chip.LENGTH-chip.LENGTH, chip.LENGTH);
		p1.lineTo(stepx*chip.LENGTH/2, stepy*chip.LENGTH/2);
		p1.lineTo(stepx*chip.LENGTH-chip.LENGTH, stepy*chip.LENGTH-chip.LENGTH);
		p1.close();
		canvas.drawPath(p1, paint);
		
		if (firstStart)
		{
			paint.setColor(Color.RED);
			paint.setTextSize(20);
			canvas.drawText("点击屏幕开始游戏", 60, 200, paint);
			canvas.drawText("触摸颜色区控制方向", 50, 260, paint);
			
		}
		if (pause)
		{
			paint.setColor(Color.RED);
			paint.setTextSize(20);
			canvas.drawText("点击游戏继续", 70, 260, paint);
			
		}
		findFood();
		for(int i=0;ichip.LENGTH*(stepx-2)||
				snake.get(0).cychip.LENGTH*(stepy-2))
		{
			return true;
		}
		for(int i=1;i

最后,一条蛇就是由这样的小碎片组成的

package org.mytest.snake;

class Chip
{
	public final int LENGTH=15;
	public int cx;
	public int cy;
	public int color;
	public Chip(int x,int y,int color)
	{
		this.cx=x;
		this.cy=y;
		this.color=color;
	}
}



你可能感兴趣的:(android贪吃蛇完整代码)