关闭

贪吃蛇小游戏(JAVA)

596人阅读 评论(0) 收藏 举报
分类:

小时候玩的游戏,贪吃蛇,还真没想过有一天我会自己去写它,不管做的如何,此刻的心情还是不错的

                            

首先自然是确定窗口的大小,定义在常量类,

代码:

package cn.zhang.snakeutil;
/**
 * 
 * @author zyq_zhang
 * 常量类,包含一些基本常量
 *
 */
public class Constant {
	public static final int ROWS = 40;//游戏窗口行数
	public static final int COLS = 40;//游戏窗口列数
	public static final int BLOCK_SIZE = 15;//蛇一小节的大小
}
其次,建立游戏窗口

代码:

package cm.zhang.snakescr;

import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import cn.zhang.snakeutil.Constant;
import cn.zhang.snakeutil.Egg;

public class MySnake extends Frame {
	private Image iBuffer;
	private Graphics gBuffer;
	private boolean flag = true;
	private boolean gameOver = false;
	private int Score = 0;
	Snake snake = new Snake(this);
	Egg e = new Egg();
	private static final long serialVersionUID = 1L;

	public MySnake(String s) {
		super(s);
	}

	public void launchFrame() {
		this.setSize(Constant.BLOCK_SIZE * Constant.COLS + 15, Constant.BLOCK_SIZE * Constant.ROWS + 7);
		this.setLocation(100, 100);
		this.setVisible(true);
		// 设置监听,关闭窗口
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		// 设置键盘监听
		this.addKeyListener(new KeyListen());
		new FrameThread().start();
	}

	class KeyListen extends KeyAdapter {
		public void keyPressed(KeyEvent e) {
			snake.keyPressed(e);
		}
	}

	/*
	 * 重画!!!
	 */
	class FrameThread extends Thread {
		public void run() {
			while (flag) {// 死循环,不断重画
				repaint();
				try {
					Thread.sleep(100);// 间隔120ms画
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
	}

	public void paint(Graphics g) {
		Color c = g.getColor();
		this.setBackground(Color.GRAY);
		g.setColor(Color.BLACK);
		for (int i = 1; i < Constant.COLS; i++) {
			g.drawLine(Constant.BLOCK_SIZE * i + 7, 0, Constant.BLOCK_SIZE * i + 7,
					Constant.BLOCK_SIZE * Constant.ROWS);
		}
		for (int i = 1; i < Constant.ROWS; i++) {
			g.drawLine(0, Constant.BLOCK_SIZE * i, Constant.BLOCK_SIZE * Constant.COLS + 8, Constant.BLOCK_SIZE * i);
		}
		g.setColor(Color.orange);
		
		if (gameOver) {
			g.setFont(new Font("宋体", Font.BOLD, 80));
			g.drawString("游戏结束", 120, 350);
			flag = false;
		}
		if(!gameOver)
		{
		g.drawString("得分:" + Score, 50, 60);
		}
		this.setVisible(true);
		snake.draw(g);
		e.draw(g);
		snake.eategg(e);
		g.setColor(c);
	}

	public int getScore() {
		return Score;
	}

	public void setScore(int score) {
		Score = score;
	}

	// JAVA双缓冲
	public void update(Graphics scr) {
		if (iBuffer == null) {
			iBuffer = createImage(this.getSize().width, this.getSize().height);
			gBuffer = iBuffer.getGraphics();
		}
		gBuffer.setColor(getBackground());
		gBuffer.fillRect(0, 0, this.getSize().width, this.getSize().height);
		paint(gBuffer);
		scr.drawImage(iBuffer, 0, 0, this);
	}

	public static void main(String[] args) {
		new MySnake("贪吃蛇").launchFrame();
	}

	public void stop() {
		gameOver = true;
	}
}
定义蛇类,关于蛇的移动,增加,其实就是在在蛇尾或者蛇头增加一节。

代码:

package cm.zhang.snakescr;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import cn.zhang.snakeutil.Constant;
import cn.zhang.snakeutil.Egg;
import cn.zhang.snakeutil.MoveDir;

public class Snake {
	Node head = null;
	Node tail = null;
	private Node N = new Node(20, 20, MoveDir.L);
	private MySnake m;
	public Snake(MySnake m) {
		this.head = N;
		this.tail = N;
		this.m=m;
	}

	public void draw(Graphics g) {
		/*	addToHead();
		dellteTotill();*/
		move();//其实它的语句就是上面两句,但是一个方法尽量只做一件事,所以把它写成一个单独的函数
		for (Node n = head; n != null; n = n.next) {
			n.draw(g);
		}
	
	}

	private void dellteTotill() {
		tail = tail.prev;
		tail.next = null;
	}

	public void addToTail() {
		Node node = null;
		switch (tail.dir) {
		case L:
			node = new Node(tail.row, tail.col + 1, tail.dir);
			break;
		case U:
			node = new Node(tail.row + 1, tail.col, tail.dir);
			break;
		case R:
			node = new Node(tail.row, tail.col - 1, tail.dir);
			break;
		case D:
			node = new Node(tail.row - 1, tail.col, tail.dir);
			break;
		}
		tail.next = node;
		node.prev = tail;
		tail= node;
	}

	public void addToHead() {
		Node node = null;
		switch (head.dir) {
		case L:
			node = new Node(head.row, head.col - 1, head.dir);
			break;
		case U:
			node = new Node(head.row - 1, head.col, head.dir);
			break;
		case R:
			node = new Node(head.row, head.col + 1, head.dir);
			break;
		case D:
			node = new Node(head.row + 1, head.col, head.dir);
			break;
		}
		node.next = head;
		head.prev = node;
		head = node;
	}

	private class Node {
		int w = Constant.BLOCK_SIZE;
		int h = Constant.BLOCK_SIZE;
		int row, col;
		MoveDir dir = MoveDir.L;
		Node next = null;
		Node prev = null;

		Node(int row, int col, MoveDir dir) {
			this.row = row;
			this.col = col;
			this.dir = dir;
		}

		void draw(Graphics g) {
			Color c = g.getColor();
			g.setColor(Color.BLACK);
			g.fillRect(Constant.BLOCK_SIZE * col + 7, Constant.BLOCK_SIZE * row, w, h);
			g.setColor(c);
		}
	}

	public void move() {
		addToHead();
		dellteTotill();
		ifDead();
	}
    
	public void eategg(Egg e){
		if(this.getRect().intersects(e.getRect()))
		{
			this.addToHead();
			e.Regenerate();
			m.setScore(m.getScore()+5);
		}
	}
	private Rectangle getRect(){
		return new Rectangle(Constant.BLOCK_SIZE * head.col + 7, Constant.BLOCK_SIZE *head.row, head.w, head.h);
	}
	
	public void ifDead(){
		//过了边界,dead
		if(head.row<0||head.row>Constant.ROWS||head.col<0||head.col>Constant.COLS){
		   m.stop();
		}
		//碰到自己身子,dead
		for(Node n = head.next; n != null; n = n.next) {
			if(head.row == n.row && head.col == n.col) {
				m.stop();
			}
		}
	}
	
	/*
	 * 蛇不能往回走
	 */
	public void keyPressed(KeyEvent e) {
		
		int key = e.getKeyCode();
		switch(key) {
		case KeyEvent.VK_LEFT :
			if(head.dir != MoveDir.R)
				head.dir = MoveDir.L;
			
			break;
		case KeyEvent.VK_UP :
			if(head.dir != MoveDir.D)
				head.dir = MoveDir.U;
			break;
		case KeyEvent.VK_RIGHT :
			if(head.dir != MoveDir.L)
				head.dir = MoveDir.R;
			break;
		case KeyEvent.VK_DOWN :
			if(head.dir != MoveDir.U)
				head.dir = MoveDir.D;
			break;
		}
	}
}

定义被蛇吃的一小格,俗称蛋,被吃一个,在随机产生一个

代码:

package cn.zhang.snakeutil;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;

public class Egg {
	int row, col;
	int w = Constant.BLOCK_SIZE;
	int h = Constant.BLOCK_SIZE;
	private static Random r = new Random();
    private Color first=Color.RED;
	public Egg(int row, int col) {
		this.row = row;
		this.col = col;
	}

	public Egg() {
		this(r.nextInt(Constant.ROWS - 2) + 2, r.nextInt(Constant.COLS));
	}

	public Rectangle getRect() {
		return new Rectangle(Constant.BLOCK_SIZE * col + 7, Constant.BLOCK_SIZE * row, w, h);
	}

	public void draw(Graphics g) {
		Color c = g.getColor();
		g.setColor(first);
		g.fillRect(Constant.BLOCK_SIZE * col + 7, Constant.BLOCK_SIZE * row, w, h);
        if(first==Color.RED) first=Color.GREEN;
        else
        	first=Color.RED;
		g.setColor(c);
	}

	public void Regenerate() {
		this.row = r.nextInt(Constant.ROWS - 2) + 2;
		this.col = r.nextInt(Constant.COLS);
	}
}

一个枚举类,蛇的运动方向

package cn.zhang.snakeutil;
/**
 * 
 * 运动方向
 *
 */
public enum MoveDir {
      L,R,U,D;
}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:18445次
    • 积分:682
    • 等级:
    • 排名:千里之外
    • 原创:51篇
    • 转载:7篇
    • 译文:0篇
    • 评论:7条
    最新评论