java 简单贪吃蛇

说了是简单版贪吃蛇。。。

就3个类+方向枚举变量(本来想写贪吃蛇斜着走的。。想象我的蛇是矩形 斜着难看就没写)

上下左右键控制移动 空格暂停

SnackClient类

package com.xynu.snaker;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class SnackClient extends JFrame {
	private static SnackClient sc;
	private SnackBody snackFood;
	//当前游戏状态
	private boolean gameState = true;
	private MyComponent mc;
	//游戏
	private boolean pause = false;
	private JMenu menu;
	private JMenuBar menubar;
	//低等级
	private JMenuItem lowSpeedItem;
	//中等级
	private JMenuItem midSpeedItem;
	//高等级
	private JMenuItem heightSpeedItem;
	//重新开始
	private JMenuItem restartItem;
	public int speed = 15;
	static int score = 0;
	private MaxScore ms;
	//蛇身子
	ArrayList<SnackBody> snackBodys = new ArrayList<SnackBody>();
	//蛇头
	static SnackBody snackHead;
	private static final long serialVersionUID = 1L;

	public SnackClient() {
		//初始化菜单栏
		initMenu();
		mc = new MyComponent();
		mc.setBackground(Color.BLACK);
		add(mc);
		setTitle("贪吃蛇");
		setSize(800, 600);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		setResizable(false);
		snackHead = new SnackBody(100, 100, this);
		for (int i = 0; i < 2; i++) {
			snackBodys.add(new SnackBody(-100, -100, this));
		}
		ms = new MaxScore();
		showSnackFood();
		addKeyListener(new MyKeyListener());
		new paintThread().start();
	}

	private void initMenu() {
		// TODO Auto-generated method stub
		menu = new JMenu("参数设置");
		lowSpeedItem = new JMenuItem("低等级");
		midSpeedItem = new JMenuItem("中等级");
		heightSpeedItem = new JMenuItem("高等级");
		restartItem=new JMenuItem("重新开始");
		lowSpeedItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				speed = 15;
			}
		});
		midSpeedItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				speed = 17;
			}
		});
		heightSpeedItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				speed = 20;
			}
		});
		restartItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				dispose();
				sc=new SnackClient();
			}
		});
		menu.add(lowSpeedItem);
		menu.add(midSpeedItem);
		menu.add(heightSpeedItem);
		menu.add(restartItem);
		menubar = new JMenuBar();
		menubar.add(menu);
		setJMenuBar(menubar);
	}

	public boolean isPause() {
		return pause;
	}

	public void setPause(boolean pause) {
		this.pause = pause;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		sc = new SnackClient();
	}

	public class MyComponent extends JPanel {

		/**
		 *
		 */
		private static final long serialVersionUID = 1L;

		protected void paintComponent(Graphics g) {
			// TODO Auto-generated method stub
			super.paintComponent(g);

			if (!gameState) {
				Font font = new Font("微软雅黑", Font.BOLD, 50);
				g.setFont(font);
				g.setColor(Color.RED);
				g.drawString("GAME OVER!!", this.getWidth() / 2 - 150,
						this.getHeight() / 2);
				return;
			}

			// 如果蛇撞到蛇身 或 撞墙 游戏结束
			if (snackHead.hitWall() || snackHead.hitSnackBody(snackBodys)) {
				gameState = false;
			}
			// 如果蛇头吃到食物
			if (snackHead.hitSnackBody(snackFood)) {
				snackBodys.add(snackFood);
				score++;
				// 刷新食物
				showSnackFood();
			}
			// 画食物
			snackFood.draw(g);
			// 画蛇身
			if (gameState) {
				for (SnackBody sb : snackBodys) {
					sb.draw(g);
				}
			}
			// 画蛇头
			if (gameState) {
				snackHead.draw(g);
			}
			try {
				g.drawString(
						"当前分数:" + score * 100 + "      游戏最高分:"
								+ ms.getMaxScore(), 0, 10);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//随机出现食物
	public void showSnackFood() {

		Random r = new Random();
		boolean exit = true;
		while (exit) {
			int x = r.nextInt(mc.getWidth() - snackHead.getWidth());
			int y = r.nextInt(mc.getHeight() - snackHead.getHeight());
			snackFood = new SnackBody(x, y, sc);
			if (snackFood.hitSnackBody(snackHead)
					|| snackFood.hitSnackBody(snackBodys)) {
				continue;
			}
			exit = false;
		}

	}
	//键盘事件
	public class MyKeyListener extends KeyAdapter {
		@Override
		public void keyPressed(KeyEvent e) {
			// TODO Auto-generated method stub
			snackHead.keyPress(e);
		}

		@Override
		public void keyReleased(KeyEvent e) {
			// TODO Auto-generated method stub
			snackHead.keyRelease(e);
		}
	}
	//游戏刷新
	public class paintThread extends Thread {
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				if (!pause) {
					repaint();
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}
		}
	}
}

封装的蛇身SnackBody类

package com.xynu.snaker;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

public class SnackBody {
	private int x;
	private int y;
	private int speed = 15;
	private int width = 15;
	private int height = 15;
	private boolean left, right, up, down;
	private Direction dir = Direction.D, curdir = Direction.D;
	private SnackClient sc;

	public SnackBody() {
		super();
		// TODO Auto-generated constructor stub
	}

	public SnackBody(int x, int y, SnackClient sc) {
		super();
		this.x = x;
		this.y = y;
		this.sc = sc;
	}

	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;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public Direction getDir() {
		return dir;
	}

	public void draw(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		Rectangle2D r2 = new Rectangle2D.Double(x, y, width, height);
		//蛇身为黄色
		g2.setColor(Color.YELLOW);
		//蛇头为红色
		if (this == SnackClient.snackHead)
			g2.setColor(Color.RED);
		g2.fill(r2);
		if (this == SnackClient.snackHead) {
			this.speed = sc.speed;
			move();
		}

	}
	//键盘事件
	public void keyPress(KeyEvent e) {
		switch (e.getKeyCode()) {
		case KeyEvent.VK_RIGHT:
			right = true;
			break;
		case KeyEvent.VK_LEFT:
			left = true;
			break;
		case KeyEvent.VK_UP:
			up = true;
			break;
		case KeyEvent.VK_DOWN:
			down = true;
			break;
		case KeyEvent.VK_SPACE:
			sc.setPause(!sc.isPause());
			break;
		}
		judgeDir();
	}
	//判断方向  如果你想八个方向移动也是同理
	private void judgeDir() {
		// TODO Auto-generated method stub
		if (left && !right && !up && !down)
			curdir = Direction.L;
		if (!left && right && !up && !down)
			curdir = Direction.R;
		if (!left && !right && up && !down)
			curdir = Direction.U;
		if (!left && !right && !up && down)
			curdir = Direction.D;
	}
	/*
	 * 蛇体的移动根据蛇身移动
	 * 第一节蛇身等于蛇头移动前的位置
	 * 第二节蛇身等于第一节蛇身移动前的位置
	 * 以此类推
	 */
	private void move() {
		if (dir == Direction.L && curdir == Direction.R)
			curdir = dir;
		if (dir == Direction.R && curdir == Direction.L)
			curdir = dir;
		if (dir == Direction.U && curdir == Direction.D)
			curdir = dir;
		if (dir == Direction.D && curdir == Direction.U)
			curdir = dir;
		if (dir != curdir)
			dir = curdir;

		int preX = x;
		int preY = y;

		if (dir == Direction.L) {
			x -= speed;
			preX += 1;
		}

		if (dir == Direction.R) {
			x += speed;
			preX -= 1;
		}

		if (dir == Direction.U) {
			y -= speed;
			preY += 1;
		}

		if (dir == Direction.D) {
			y += speed;
			preY -= 1;
		}
		int tempX, tempY;
		for (SnackBody body : sc.snackBodys) {
			tempX = body.getX();
			tempY = body.getY();
			body.setX(preX);
			body.setY(preY);
			preX = tempX;
			preY = tempY;
		}
	}

	public void keyRelease(KeyEvent e) {
		switch (e.getKeyCode()) {
		case KeyEvent.VK_RIGHT:
			right = false;
			break;
		case KeyEvent.VK_LEFT:
			left = false;
			break;
		case KeyEvent.VK_UP:
			up = false;
			break;
		case KeyEvent.VK_DOWN:
			down = false;
			break;
		}
	}
	//返回蛇身矩形
	public Rectangle getRec() {
		return new Rectangle(x, y, width, height);
	}
	//蛇头和蛇身的碰撞事件
	public boolean hitSnackBody(SnackBody sb) {
		if (this == sb)
			return false;
		if (this.getRec().intersects(sb.getRec())) {
			return true;
		}
		return false;
	}

	public boolean hitSnackBody(ArrayList<SnackBody> snackBodys) {
		for (SnackBody snackBody : snackBodys) {
			if (this != snackBody) {
				if (hitSnackBody(snackBody)) {
					return true;
				}
			}
		}
		return false;
	}

	public boolean hitWall() {
		if (x <= 0 || y <= 0 || x >= sc.getWidth() - width
				|| y >= sc.getHeight() - height) {
			return true;
		}
		return false;
	}
}

最高分MaxScore类

package com.xynu.snaker;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MaxScore {
	public int getMaxScore() throws IOException{
		File file=new File("maxScore.txt");
		if(!file.exists()){
			file.createNewFile();

		}
		BufferedReader br=new BufferedReader(new FileReader(file));
		String s=br.readLine();
		int max=0;
		if(!"".equals(s)&&s!=null){
			max=Integer.parseInt(s);
		}
		else{
			max=0;
		}
		if(SnackClient.score*100>max){
			max=SnackClient.score*100;
			BufferedWriter bw=new BufferedWriter(new FileWriter(file));
			bw.write(max+"");
			bw.close();
		}
		br.close();
		return max;
	}
}

运行结果

时间: 2024-12-28 21:15:44

java 简单贪吃蛇的相关文章

Java版贪吃蛇小游戏的实现

使用的IDE eclipse JDK版本 1.6 辅助类 Coordinate.java package com.nn.util; /** *坐标点 */ public class Coordinate { public int x; public int y; public Coordinate(int newX, int newY) { x = newX; y = newY; } public boolean equals(Coordinate other) { if (x == other

Java实现贪吃蛇游戏【代码】

花了两个下午写了一个贪吃蛇小游戏,本人想写这游戏很长时间了.作为以前诺基亚手机上的经典游戏,贪吃蛇和俄罗斯方块一样,都曾经在我们的童年给我们带来了很多乐趣.世间万物斗转星移,诺基亚曾经作为手机业的龙头老大,现如今也一步步走向衰落,被收购,再过不久估计就要退出手机业务了,而贪吃蛇这款游戏也基本上没人玩了,甚至在新一代人的印象中都已毫无记忆了...但是,这款游戏在它基础上经过改造其实可以弄出很多花样,也确实可以在一定程度上锻炼自己的编程能力.前不久十分火热的贪吃蛇大作战其实就可以看做是在这款游戏的基

Java版贪吃蛇(比较完善的版本)

很认真的写的一个java版的贪吃蛇游戏,图形界面,支持菜单操作,键盘监听,可加速,减速,统计得分,设定运动速度,设定游戏背景颜色等!应该没有Bug了,因为全被我修改没了.哈哈. 下面是项目各包及类的层次关系: 游戏的主要运行界面截图如下: 下面是部分代码,详细源码见此链接:http://pan.baidu.com/s/1bnubnzh //Snake类: package com.huowolf.entities; import java.awt.Color; import java.awt.Gr

用Java开发贪吃蛇游戏

贪吃蛇游戏的设计步骤: Part 1: 设计游戏图纸 画出900*700的白色窗口 在窗口上添加画布 在画布上添加标题 在画布上添加黑色游戏区 Part 2: 放置静态的蛇:一个头.两个身体 加上开始提示:按空格键开始游戏 让蛇动起来:监听Timer事件,平移数据 实现游戏暂停 实现转向功能 Part 3: 添加食物 吃掉食物 添加死亡条件 实现“重新开始”功能 添加分数和长度 游戏图纸如下: 蛇及游戏框的素材如下:                              Snake主类: 1

JavaScript实现简单贪吃蛇小游戏

之前上Web课,学到JavaScript的时候,老师要求写几个静态页面,要用到JavaScript.想了想就写个贪吃蛇吧.其实之前用pygame写过一次GUI的贪吃蛇,素材都是自己拿画图画的,其丑无比.所以这次还是老老实实用字符吧. 首先,是一些全局变量的定义: 1 <script> 2 var state = 0;//0 wait 1 run 2 over 3 var width = 40; 4 var height = 25; 5 var update = false; 6 var dir

简单贪吃蛇

在游戏开始时,分数为0,游戏结束时会弹出分数. 代码: <!DOCTYPE html><html><head><meta charset="UTF-8"><title>贪吃蛇</title><style>*{padding: 0;margin: 0;}#layer{border-collapse:collapse; border-spacing:0;}#layer td{width: 40px;heig

简单贪吃蛇游戏js

新手,仿照别人的写的.只能实现简单的功能,代码如下: 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <title></title> 6 <style> 7 *{ 8 margin: 0; 9 padding: 0; 10 } 11 #box{ 12 position: absolute; 13 left: 0; 14 t

java版贪吃蛇

界面:大红色方块----蛇头,绿色----身体,粉色----食物 package com.snake; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import j

C++简单贪吃蛇实现

#include <iostream> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <deque> #include <list> #define _SIZE_ 30 #define _SET_ cout<<"\033[?25l\033[0m" static int flags = 0; typedef int