Java实现贪吃蛇游戏【代码】
花了两个下午写了一个贪吃蛇小游戏,本人想写这游戏很长时间了。作为以前诺基亚手机上的经典游戏,贪吃蛇和俄罗斯方块一样,都曾经在我们的童年给我们带来了很多乐趣。世间万物斗转星移,诺基亚曾经作为手机业的龙头老大,现如今也一步步走向衰落,被收购,再过不久估计就要退出手机业务了,而贪吃蛇这款游戏也基本上没人玩了,甚至在新一代人的印象中都已毫无记忆了。。。但是,这款游戏在它基础上经过改造其实可以弄出很多花样,也确实可以在一定程度上锻炼自己的编程能力。前不久十分火热的贪吃蛇大作战其实就可以看做是在这款游戏的基础上进行的改造。所以,我也希望自己可以尝试以下,做个有意思的版本。
目前这个版本只是为了后期版本的一个测试版本,所以只有一些基本功能,本来是打算这个版本实现了移动,吃食物增长,判断撞墙和撞自己的身体就行了,无奈觉得有点单调,于是在此基础上加上了一个计时器,记分功能,重新开始,开始暂停以及音效。白白又多了几百行代码。原来的基本代码也就300行。
游戏界面图如下:
注意运行时请附带以下文件:
http://files.cnblogs.com/files/journal-of-xjx/SnakeDemo.rar
以后版本更新都将放到 Github:
https://github.com/JiaxinTse/Snake
另外,第四版的游戏截图请看下一篇文章,比此处的Demo版丰富了很多:
http://www.cnblogs.com/journal-of-xjx/p/7217799.html
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.sound.sampled.*;
import javax.swing.*; class Tile{
int x;
int y; public Tile(int x0,int y0){
x = x0;
y = y0;
}
} public class SnakeDemo extends JComponent{
/**
*
*/
private static final long serialVersionUID = 3794762291171148906L;
private final int MAX_SIZE = 400;//蛇身体最长为400节
private Tile temp = new Tile(0,0);
private Tile temp2 = new Tile(0,0);
private Tile head = new Tile(227,100);//头部的位置初始化为(227,100)
private Tile[] body = new Tile[MAX_SIZE];
private String direction = "R";//默认向右走
private String current_direction = "R";//当前方向
private boolean first_launch = false;
private boolean iseaten = false;
private boolean isrun = true;
private int randomx,randomy;
private int body_length = 5;//身体长度初始化为5
private Thread run;
private JLabel label = new JLabel("当前长度:");
private JLabel label2 = new JLabel("所花时间:");
private JLabel label3 = new JLabel("说 明:");
private JTextArea explain = new JTextArea("此游戏是一个贪吃蛇Demo版本,实现简单地移动,得分,判断撞墙和撞自己的功能,"
+ "初始长度为6,头部为红色,身体的颜色渐变。游戏本身代码只有300行,加上一些显示,计时和音效后多了几百行。\n"
+ "游戏界面按上下左右键实现移动,按ESC重新开始,按空格键可以实现暂停和开始");
private JLabel Score = new JLabel("6");
private JLabel Time = new JLabel("");
private Font f = new Font("微软雅黑",Font.PLAIN,15);
private Font f2 = new Font("微软雅黑",Font.PLAIN,13);
private JPanel p = new JPanel();
private int hour =0;
private int min =0;
private int sec =0 ;
private boolean pause = false; public SnakeDemo(){
String lookAndFeel =UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(lookAndFeel);
} catch (ClassNotFoundException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
} catch (InstantiationException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
} //布局
add(label);
label.setBounds(500, 10, 80, 20);
label.setFont(f);
add(Score);
Score.setBounds(500, 35, 80, 20);
Score.setFont(f);
add(label2);
label2.setBounds(500, 60, 80, 20);
label2.setFont(f);
add(Time);
Time.setBounds(500, 85, 80, 20);
Time.setFont(f);
add(p);
p.setBounds(498, 110, 93, 1);
p.setBorder(BorderFactory.createLineBorder(Color.black)); add(label3);
label3.setBounds(500, 115, 80, 20);
label3.setFont(f);
add(explain);
explain.setBounds(498, 138, 100, 350);
explain.setFont(f2);
explain.setLineWrap(true);
explain.setOpaque(false); for(int i = 0; i < MAX_SIZE;i++)
{
body[i] = new Tile(0,0);
} addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(isrun && current_direction != "L")
{
direction = "R";
}
}
if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(isrun && current_direction != "R")
{
direction = "L";
}
}
if(e.getKeyCode() == KeyEvent.VK_UP)
{
if(isrun && current_direction != "D")
{
direction = "U";
}
}
if(e.getKeyCode() == KeyEvent.VK_DOWN)
{
if(isrun && current_direction != "U")
{
direction = "D";
}
}
if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int i = 0; i < MAX_SIZE;i++)
{
body[i].x = 0;
body[i].y = 0;
} run = new Thread();
run.start();
System.out.println("Start again");
}
if(e.getKeyCode() == KeyEvent.VK_SPACE)//按空格键开始和暂停暂时没做,还在思考中
{
if(!pause)//暂停
{
pause = true;
isrun = false;
}
else//开始
{
pause = false;
isrun = true;
}
}
}
}); new Timer(); setFocusable(true);
} public void paintComponent(Graphics g1){
super.paintComponent(g1);
Graphics2D g = (Graphics2D) g1;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,RenderingHints.VALUE_STROKE_NORMALIZE); //画头部
g.setColor(Color.red);
g.fillRoundRect(head.x, head.y, 20, 20, 10, 10); g.setPaint(new GradientPaint(115,135,Color.CYAN,230,135,Color.MAGENTA,true));
if(!first_launch)
{
//初始化身体
int x = head.x;
for(int i = 0;i < body_length;i++)
{
x -= 22;//相邻两个方块的间距为2个像素,方块宽度都为20像素
body[i].x = x;
body[i].y = head.y;
g.fillRoundRect(body[i].x, body[i].y, 20, 20, 10, 10);
}
//初始化食物位置
ProduceRandom();
g.fillOval(randomx, randomy, 19, 19);
}
else
{
//每次刷新身体
for(int i = 0;i < body_length;i++)
{
g.fillRoundRect(body[i].x, body[i].y, 20, 20, 10, 10);
} if(EatFood())//被吃了重新产生食物
{
ProduceRandom();
g.fillOval(randomx, randomy, 19, 19);
iseaten = false;
}
else
{
g.fillOval(randomx, randomy, 19, 19);
}
}
first_launch = true;
//墙
g.setStroke( new BasicStroke(4,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL));
g.setBackground(Color.black);
g.drawRect(2, 7, 491, 469); //网格线
for(int i = 1;i < 22;i++)
{
g.setStroke( new BasicStroke(1,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL));
g.setColor(Color.black);
g.drawLine(5+i*22,9,5+i*22,472);
if(i <= 20)
{
g.drawLine(4,10+i*22,491,10+i*22);
}
}
} public void ProduceRandom(){
boolean flag = true;
Random rand = new Random();
randomx = (rand.nextInt(21) + 1) * 22 + 7;
randomy = (rand.nextInt(20) + 1) *22 + 12;
while(flag)
{
for(int i = 0;i < body_length; i++)
{
if(body[i].x == randomx && body[i].y == randomy)
{
randomx = (rand.nextInt(21) + 1) * 22 + 7;
randomy = (rand.nextInt(20) + 1) *22 + 12;
flag = true;
break;
}
else
{
if(i == body_length - 1)
{
flag = false;
}
}
}
}
} public void HitWall(){//判断是否撞墙
if(current_direction == "L")
{
if(head.x < 7)
{
new AePlayWave("over.wav").start();
isrun = false;
int result=JOptionPane.showConfirmDialog(null, "Game over! Try again?", "Information", JOptionPane.YES_NO_OPTION);
if(result==JOptionPane.YES_NO_OPTION)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int i = 0; i < MAX_SIZE;i++)
{
body[i].x = 0;
body[i].y = 0;
} run = new Thread();
run.start();
System.out.println("Start again");
}
else
{
run.stop();
}
}
}
if(current_direction == "R")
{
if(head.x > 489)
{
new AePlayWave("over.wav").start();
isrun = false;
int result=JOptionPane.showConfirmDialog(null, "Game over! Try again?", "Information", JOptionPane.YES_NO_OPTION);
if(result==JOptionPane.YES_NO_OPTION)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int i = 0; i < MAX_SIZE;i++)
{
body[i].x = 0;
body[i].y = 0;
} run = new Thread();
run.start();
System.out.println("Start again");
}
else
{
run.stop();
}
}
}
if(current_direction == "U")
{
if(head.y < 12)
{
new AePlayWave("over.wav").start();
isrun = false;
int result=JOptionPane.showConfirmDialog(null, "Game over! Try again?", "Information", JOptionPane.YES_NO_OPTION);
if(result==JOptionPane.YES_NO_OPTION)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int i = 0; i < MAX_SIZE;i++)
{
body[i].x = 0;
body[i].y = 0;
} run = new Thread();
run.start();
System.out.println("Start again");
}
else
{
run.stop();
}
}
}
if(current_direction == "D")
{
if(head.y > 472)
{
new AePlayWave("over.wav").start();
isrun = false;
int result=JOptionPane.showConfirmDialog(null, "Game over! Try again?", "Information", JOptionPane.YES_NO_OPTION);
if(result==JOptionPane.YES_NO_OPTION)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int i = 0; i < MAX_SIZE;i++)
{
body[i].x = 0;
body[i].y = 0;
} run = new Thread();
run.start();
System.out.println("Start again");
}
else
{
run.stop();
}
}
}
} public void HitSelf(){//判断是否撞到自己身上
for(int i = 0;i < body_length; i++)
{
if(body[i].x == head.x && body[i].y == head.y)
{
new AePlayWave("over.wav").start();
isrun = false;
int result=JOptionPane.showConfirmDialog(null, "Game over! Try again?", "Information", JOptionPane.YES_NO_OPTION);
if(result==JOptionPane.YES_NO_OPTION)
{
direction = "R";//默认向右走
current_direction = "R";//当前方向
first_launch = false;
iseaten = false;
isrun = true;
body_length = 5;
head = new Tile(227,100);
Score.setText("6");
hour =0;
min =0;
sec =0 ;
for(int j = 0; j < MAX_SIZE;j++)
{
body[j].x = 0;
body[j].y = 0;
} run = new Thread();
run.start();
System.out.println("Start again");
}
else
{
run.stop();
}
break;
}
}
} public boolean EatFood(){
if(head.x == randomx && head.y == randomy)
{
iseaten = true;
return true;
}
else
{
return false;
}
} public void Thread(){
long millis = 300;//每隔300毫秒刷新一次
run = new Thread() {
public void run() {
while (true)
{
try {
Thread.sleep(millis);
} catch (InterruptedException ex) {
ex.printStackTrace();
} if(!pause)
{
temp.x = head.x;
temp.y = head.y;
//头部移动
if(direction == "L")
{
head.x -= 22;
}
if(direction == "R")
{
head.x += 22;
}
if(direction == "U")
{
head.y -= 22;
}
if(direction == "D")
{
head.y += 22;
}
current_direction = direction;//刷新当前前进方向
//身体移动
for(int i = 0;i < body_length;i++)
{
temp2.x = body[i].x;
temp2.y = body[i].y;
body[i].x = temp.x;
body[i].y = temp.y;
temp.x = temp2.x;
temp.y = temp2.y;
} if(EatFood())
{
body_length ++;
body[body_length-1].x = temp2.x;
body[body_length-1].y = temp2.y;
Score.setText("" + (body_length+1) );
new AePlayWave("eat.wav").start();
} repaint(); HitWall();
HitSelf();
}
}
}
}; run.start();
} public static void main(String[] args) {
SnakeDemo t = new SnakeDemo();
t.Thread(); JFrame game = new JFrame();
Image img=Toolkit.getDefaultToolkit().getImage("title.png");//窗口图标
game.setIconImage(img);
game.setTitle("Snake By XJX");
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// game.setSize(502, 507);
game.setSize(602, 507);
game.setResizable(false);
game.setLocationRelativeTo(null); game.add(t);
game.setVisible(true);
} //计时器类
class Timer extends Thread{
public Timer(){
this.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
if(isrun){
sec +=1 ;
if(sec >= 60){
sec = 0;
min +=1 ;
}
if(min>=60){
min=0;
hour+=1;
}
showTime();
} try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
} private void showTime(){
String strTime ="" ;
if(hour < 10)
strTime = "0"+hour+":";
else
strTime = ""+hour+":"; if(min < 10)
strTime = strTime+"0"+min+":";
else
strTime =strTime+ ""+min+":"; if(sec < 10)
strTime = strTime+"0"+sec;
else
strTime = strTime+""+sec; //在窗体上设置显示时间
Time.setText(strTime);
}
}
} class AePlayWave extends Thread {
private String filename;
private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb public AePlayWave(String wavfile) {
filename = wavfile;
} public void run() {
File soundFile = new File(filename);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
} AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
} auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}
Java实现贪吃蛇游戏【代码】的更多相关文章
- 用Java开发贪吃蛇游戏
贪吃蛇游戏的设计步骤: Part 1: 设计游戏图纸 画出900*700的白色窗口 在窗口上添加画布 在画布上添加标题 在画布上添加黑色游戏区 Part 2: 放置静态的蛇:一个头.两个身体 加上开始 ...
- Java实现贪吃蛇游戏(含账号注册登录,排行榜功能)
这是我第一次工程实践的作业,选题很多,但我只对其中的游戏开发感兴趣,可游戏就两三个类型,最终还是选择了贪吃蛇.其实就贪吃蛇本身的代码实现还算是比较简单的,可是实践要求代码行达到一定数量,所以我就额外给 ...
- java实现贪吃蛇游戏
最简单的4个java类就可以实现贪吃蛇: main函数: package tcs; public class GreedSnake { public static void main(String[] ...
- python学习笔记05:贪吃蛇游戏代码
贪吃蛇游戏截图: 首先安装pygame,可以使用pip安装pygame: pip install pygame 运行以下代码即可: #!/usr/bin/env python import pygam ...
- 用OpenGL简单编写的一个最简单贪吃蛇游戏
刚学OpenGL的时候,写的一个最简单的贪吃蛇游戏代码 如下: //贪吃蛇游戏 #include<stdio.h> #include<stdlib.h> #include< ...
- Love2D游戏引擎制作贪吃蛇游戏
代码地址如下:http://www.demodashi.com/demo/15051.html Love2D游戏引擎制作贪吃蛇游戏 内附有linux下的makefile,windows下的生成方法请查 ...
- Java贪吃蛇游戏
package snake.game; import java.awt.CardLayout; import java.awt.Color; import java.awt.Graphics; i ...
- 使用Java的GUI技术实现 “ 贪吃蛇 ” 游戏
详细教程: 使用Java的GUI技术实现 " 贪吃蛇 " 游戏_IT打工酱的博客-CSDN博客
- Android快乐贪吃蛇游戏实战项目开发教程-01项目概述与目录
一.项目简介 贪吃蛇是一个很经典的游戏,也很适合用来学习.本教程将和大家一起做一个Android版的贪吃蛇游戏. 我已经将做好的案例上传到了应用宝,无病毒.无广告,大家可以放心下载下来把玩一下.应用宝 ...
随机推荐
- 防止UI穿透操作到游戏场景
#if UNITY_EDITOR || UNITY_STANDALONE_WIN if (EventSystem.current.IsPointerOverGameObject()) { return ...
- always中的敏感变量
always语句下如果有判断语句if,那么if语句中的条件必须有always中的敏感变量. 否则错误提示为:Error (10200): Verilog HDL Conditional Stateme ...
- Windows和Linux环境下搭建SVN服务器
--------------------------Windows下搭建SVN服务器----------------------------- 一.安装SVN服务端 软件包Setup-Subversi ...
- 1.python的安装
1.python 安装实验所用为系统自带,退出为exit() 或ctrl +D命令 2.一般装pyhton2.7 ,3.5的版本有更多特效.不用在版本上太多纠结.python官网https://www ...
- [Android] AutoCompleteTextView:自己主动完毕输入内容的控件(自己主动补全)
AutoCompleteTextView是EditText的直接子类,与普通EditText的最大不同就是.在用户输入的过程中,能够列出可供选择的输入项.方便使用者. AutoCompleteText ...
- http get(swift and oc)
SynchonousRequest: let urlPath: String = "http://www.weather.com.cn/data/sk/101010100.html" ...
- 阿里巴巴2016研发project师笔试题
问题1: 假设下列的公式成立:78+78=123,则採用的是_______进制表示的. 本题实则考察进制转换.能够设为x进制.可是x进制有一个问题.即我们无法对x进制直接进行加减乘除.故转化为我们常见 ...
- SharePoint 集成OWA概述
简介 OWA服务,也就是Office Web Application,微软提供的可以在线查看和编辑Office系列文档的服务,包括Word/Excel/PPT/OneNote.我们可以通过OWA服务和 ...
- springboot定时任务——整合Quartz
http://blog.csdn.net/liuchuanhong1/article/details/60873295 http://blog.csdn.net/lyg_come_on/article ...
- 你懂AI吗(1)
那场载入史册的战争之后,AI成为地球的主人已经快一个世纪了. 随着见证这场战争的那一代人基本消失,除了几个要堵上人类的尊严,颠覆AI的邪恶统治的组织外,现在的人基本已经习惯了这个AI统治的世界. AI ...