-
2021-02-12 11:29:18
展开全部
连连看的小源码
package Lianliankan;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class lianliankan implements ActionListener
{
JFrame mainFrame; //主面板
Container thisContainer;
JPanel centerPanel,southPanel,northPanel; //子面板
JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组
JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮
JLabel fractionLable=new JLabel("0"); //分数标签
JButton firstButton,secondButton; //分别记录两次62616964757a686964616fe59b9ee7ad9431333335326239被选中的按钮
int grid[][] = new int[8][7];//储存游戏按钮位置
static boolean pressInformation=false; //判断是否有按钮被选中
int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戏按钮的位置坐标
int i,j,k,n;//消除方法控制
public void init(){
mainFrame=new JFrame("JKJ连连看");
thisContainer = mainFrame.getContentPane();
thisContainer.setLayout(new BorderLayout());
centerPanel=new JPanel();
southPanel=new JPanel();
northPanel=new JPanel();
thisContainer.add(centerPanel,"Center");
thisContainer.add(southPanel,"South");
thisContainer.add(northPanel,"North");
centerPanel.setLayout(new GridLayout(6,5));
for(int cols = 0;cols < 6;cols++){
for(int rows = 0;rows < 5;rows++ ){
diamondsButton[cols][rows]=new JButton(String.valueOf(grid[cols+1][rows+1]));
diamondsButton[cols][rows].addActionListener(this);
centerPanel.add(diamondsButton[cols][rows]);
}
}
exitButton=new JButton("退出");
exitButton.addActionListener(this);
resetButton=new JButton("重列");
resetButton.addActionListener(this);
newlyButton=new JButton("再来一局");
newlyButton.addActionListener(this);
southPanel.add(exitButton);
southPanel.add(resetButton);
southPanel.add(newlyButton);
fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText())));
northPanel.add(fractionLable);
mainFrame.setBounds(280,100,500,450);
mainFrame.setVisible(true);
}
public void randomBuild() {
int randoms,cols,rows;
for(int twins=1;twins<=15;twins++) {
randoms=(int)(Math.random()*25+1);
for(int alike=1;alike<=2;alike++) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
while(grid[cols][rows]!=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
}
this.grid[cols][rows]=randoms;
}
}
}
public void fraction(){
fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText())+100));
}
public void reload() {
int save[] = new int[30];
int n=0,cols,rows;
int grid[][]= new int[8][7];
for(int i=0;i<=6;i++) {
for(int j=0;j<=5;j++) {
if(this.grid[i][j]!=0) {
save[n]=this.grid[i][j];
n++;
}
}
}
n=n-1;
this.grid=grid;
while(n>=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
while(grid[cols][rows]!=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
}
this.grid[cols][rows]=save[n];
n--;
}
mainFrame.setVisible(false);
pressInformation=false; //这里一定要将按钮点击信息归为初始
init();
for(int i = 0;i < 6;i++){
for(int j = 0;j < 5;j++ ){
if(grid[i+1][j+1]==0)
diamondsButton[i][j].setVisible(false);
}
}
}
public void estimateEven(int placeX,int placeY,JButton bz) {
if(pressInformation==false) {
x=placeX;
y=placeY;
secondMsg=grid[x][y];
secondButton=bz;
pressInformation=true;
}
else {
x0=x;
y0=y;
fristMsg=secondMsg;
firstButton=secondButton;
x=placeX;
y=placeY;
secondMsg=grid[x][y];
secondButton=bz;
if(fristMsg==secondMsg && secondButton!=firstButton){
xiao();
}
}
}
public void xiao() { //相同的情况下能不能消去。仔细分析,不一条条注释
if((x0==x &&(y0==y+1||y0==y-1)) || ((x0==x+1||x0==x-1)&&(y0==y))){ //判断是否相邻
remove();
}
else{
for (j=0;j<7;j++ ) {
if (grid[x0][j]==0){ //判断第一个按钮同行哪个按钮为空
if (y>j) { //如果第二个按钮的Y坐标大于空按钮的Y坐标说明第一按钮在第二按钮左边
for (i=y-1;i>=j;i-- ){ //判断第二按钮左侧直到第一按钮中间有没有按钮
if (grid[x][i]!=0) {
k=0;
break;
}
else{ k=1; } //K=1说明通过了第一次验证
}
if (k==1) {
linePassOne();
}
}
if (y
for (i=y+1;i<=j ;i++ ){ //判断第二按钮左侧直到第一按钮中间有没有按钮
if (grid[x][i]!=0){
k=0;
break;
}
else { k=1; }
}
if (k==1){
linePassOne();
}
}
if (y==j ) {
linePassOne();
}
}
if (k==2) {
if (x0==x) {
remove();
}
if (x0
for (n=x0;n<=x-1;n++ ) {
if (grid[n][j]!=0) {
k=0;
break;
}
if(grid[n][j]==0 && n==x-1) {
remove();
}
}
}
if (x0>x) {
for (n=x0;n>=x+1 ;n-- ) {
if (grid[n][j]!=0) {
k=0;
break;
}
if(grid[n][j]==0 && n==x+1) {
remove();
}
}
}
}
}
for (i=0;i<8;i++ ) { //列
if (grid[i][y0]==0) {
if (x>i) {
for (j=x-1;j>=i ;j-- ) {
if (grid[j][y]!=0) {
k=0;
break;
}
else { k=1; }
}
if (k==1) {
rowPassOne();
}
}
if (x
for (j=x+1;j<=i;j++ ) {
if (grid[j][y]!=0) {
k=0;
break;
}
else { k=1; }
}
if (k==1) {
rowPassOne();
}
}
if (x==i) {
rowPassOne();
}
}
if (k==2){
if (y0==y) {
remove();
}
if (y0
for (n=y0;n<=y-1 ;n++ ) {
if (grid[i][n]!=0) {
k=0;
break;
}
if(grid[i][n]==0 && n==y-1) {
remove();
}
}
}
if (y0>y) {
for (n=y0;n>=y+1 ;n--) {
if (grid[i][n]!=0) {
k=0;
break;
}
if(grid[i][n]==0 && n==y+1) {
remove();
}
}
}
}
}
}
}
public void linePassOne(){
if (y0>j){ //第一按钮同行空按钮在左边
for (i=y0-1;i>=j ;i-- ){ //判断第一按钮同左侧空按钮之间有没按钮
if (grid[x0][i]!=0) {
k=0;
break;
}
else { k=2; } //K=2说明通过了第二次验证
}
}
if (y0
for (i=y0+1;i<=j ;i++){
if (grid[x0][i]!=0) {
k=0;
break;
}
else{ k=2; }
}
}
}
public void rowPassOne(){
if (x0>i) {
for (j=x0-1;j>=i ;j-- ) {
if (grid[j][y0]!=0) {
k=0;
break;
}
else { k=2; }
}
}
if (x0
for (j=x0+1;j<=i ;j++ ) {
if (grid[j][y0]!=0) {
k=0;
break;
}
else { k=2; }
}
}
}
public void remove(){
firstButton.setVisible(false);
secondButton.setVisible(false);
fraction();
pressInformation=false;
k=0;
grid[x0][y0]=0;
grid[x][y]=0;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==newlyButton){
int grid[][] = new int[8][7];
this.grid = grid;
randomBuild();
mainFrame.setVisible(false);
pressInformation=false;
init();
}
if(e.getSource()==exitButton)
System.exit(0);
if(e.getSource()==resetButton)
reload();
for(int cols = 0;cols < 6;cols++){
for(int rows = 0;rows < 5;rows++ ){
if(e.getSource()==diamondsButton[cols][rows])
estimateEven(cols+1,rows+1,diamondsButton[cols][rows]);
}
}
}
public static void main(String[] args) {
lianliankan llk = new lianliankan();
llk.randomBuild();
llk.init();
}
}
//old 998 lines
//new 318 lines
已赞过
已踩过<
你对这个回答的评价是?
评论
收起
更多相关内容 -
Java简单小游戏代码
2017-11-03 11:34:19简单的java小游戏 适合初学者 具有启蒙的作用 初学者可以来看看 -
java简单小游戏代码
2010-01-06 19:30:44java简单小游戏代码,新手可以看看!我也是刚刚学的!多多指教!!!! -
JAVA实现贪吃蛇小游戏代码包
2020-05-23 09:32:45使用JAVA编程语言实现贪吃蛇小游戏。JAVA的GUI界面编程的第一步!JAVA实现贪吃蛇小游戏代码包。三个类即可轻松实现。 -
java游戏源代码:11个小游戏的源码集合
2019-11-04 17:32:08包括以下游戏的源码:沙漠阻击手,3D魔方游戏,财富城市,贪吃蛇,俄罗斯方块,麻将,三维迷宫,扫雷,推箱子,算卦游戏和简单回合游戏11个游戏的源码,欢迎下载,供学习与交流。 -
求一个简单的Java小游戏的代码
2021-02-12 10:21:10展开全部连连看的小源码package Lianliankan;import javax.swing.*;import java.awt.*;import java.awt.event.*;public class lianliankan implements ActionListener{JFrame mainFrame; //主面...展开全部
连连看的小源码
package Lianliankan;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class lianliankan implements ActionListener
{
JFrame mainFrame; //主面32313133353236313431303231363533e58685e5aeb931333335326239板
Container thisContainer;
JPanel centerPanel,southPanel,northPanel; //子面板
JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组
JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮
JLabel fractionLable=new JLabel("0"); //分数标签
JButton firstButton,secondButton; //分别记录两次被选中的按钮
int grid[][] = new int[8][7];//储存游戏按钮位置
static boolean pressInformation=false; //判断是否有按钮被选中
int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戏按钮的位置坐标
int i,j,k,n;//消除方法控制
public void init(){
mainFrame=new JFrame("JKJ连连看");
thisContainer = mainFrame.getContentPane();
thisContainer.setLayout(new BorderLayout());
centerPanel=new JPanel();
southPanel=new JPanel();
northPanel=new JPanel();
thisContainer.add(centerPanel,"Center");
thisContainer.add(southPanel,"South");
thisContainer.add(northPanel,"North");
centerPanel.setLayout(new GridLayout(6,5));
for(int cols = 0;cols < 6;cols++){
for(int rows = 0;rows < 5;rows++ ){
diamondsButton[cols][rows]=new JButton(String.valueOf(grid[cols+1][rows+1]));
diamondsButton[cols][rows].addActionListener(this);
centerPanel.add(diamondsButton[cols][rows]);
}
}
exitButton=new JButton("退出");
exitButton.addActionListener(this);
resetButton=new JButton("重列");
resetButton.addActionListener(this);
newlyButton=new JButton("再来一局");
newlyButton.addActionListener(this);
southPanel.add(exitButton);
southPanel.add(resetButton);
southPanel.add(newlyButton);
fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText())));
northPanel.add(fractionLable);
mainFrame.setBounds(280,100,500,450);
mainFrame.setVisible(true);
}
public void randomBuild() {
int randoms,cols,rows;
for(int twins=1;twins<=15;twins++) {
randoms=(int)(Math.random()*25+1);
for(int alike=1;alike<=2;alike++) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
while(grid[cols][rows]!=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
}
this.grid[cols][rows]=randoms;
}
}
}
public void fraction(){
fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText())+100));
}
public void reload() {
int save[] = new int[30];
int n=0,cols,rows;
int grid[][]= new int[8][7];
for(int i=0;i<=6;i++) {
for(int j=0;j<=5;j++) {
if(this.grid[i][j]!=0) {
save[n]=this.grid[i][j];
n++;
}
}
}
n=n-1;
this.grid=grid;
while(n>=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
while(grid[cols][rows]!=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
}
this.grid[cols][rows]=save[n];
n--;
}
mainFrame.setVisible(false);
pressInformation=false; //这里一定要将按钮点击信息归为初始
init();
for(int i = 0;i < 6;i++){
for(int j = 0;j < 5;j++ ){
if(grid[i+1][j+1]==0)
diamondsButton[i][j].setVisible(false);
}
}
}
public void estimateEven(int placeX,int placeY,JButton bz) {
if(pressInformation==false) {
x=placeX;
y=placeY;
secondMsg=grid[x][y];
secondButton=bz;
pressInformation=true;
}
else {
x0=x;
y0=y;
fristMsg=secondMsg;
firstButton=secondButton;
x=placeX;
y=placeY;
secondMsg=grid[x][y];
secondButton=bz;
if(fristMsg==secondMsg && secondButton!=firstButton){
xiao();
}
}
}
public void xiao() { //相同的情况下能不能消去。仔细分析,不一条条注释
if((x0==x &&(y0==y+1||y0==y-1)) || ((x0==x+1||x0==x-1)&&(y0==y))){ //判断是否相邻
remove();
}
else{
for (j=0;j<7;j++ ) {
if (grid[x0][j]==0){ //判断第一个按钮同行哪个按钮为空
if (y>j) { //如果第二个按钮的Y坐标大于空按钮的Y坐标说明第一按钮在第二按钮左边
for (i=y-1;i>=j;i-- ){ //判断第二按钮左侧直到第一按钮中间有没有按钮
if (grid[x][i]!=0) {
k=0;
break;
}
else{ k=1; } //K=1说明通过了第一次验证
}
if (k==1) {
linePassOne();
}
}
if (y
for (i=y+1;i<=j ;i++ ){ //判断第二按钮左侧直到第一按钮中间有没有按钮
if (grid[x][i]!=0){
k=0;
break;
}
else { k=1; }
}
if (k==1){
linePassOne();
}
}
if (y==j ) {
linePassOne();
}
}
if (k==2) {
if (x0==x) {
remove();
}
if (x0
for (n=x0;n<=x-1;n++ ) {
if (grid[n][j]!=0) {
k=0;
break;
}
if(grid[n][j]==0 && n==x-1) {
remove();
}
}
}
if (x0>x) {
for (n=x0;n>=x+1 ;n-- ) {
if (grid[n][j]!=0) {
k=0;
break;
}
if(grid[n][j]==0 && n==x+1) {
remove();
}
}
}
}
}
for (i=0;i<8;i++ ) { //列
if (grid[i][y0]==0) {
if (x>i) {
for (j=x-1;j>=i ;j-- ) {
if (grid[j][y]!=0) {
k=0;
break;
}
else { k=1; }
}
if (k==1) {
rowPassOne();
}
}
if (x
for (j=x+1;j<=i;j++ ) {
if (grid[j][y]!=0) {
k=0;
break;
}
else { k=1; }
}
if (k==1) {
rowPassOne();
}
}
if (x==i) {
rowPassOne();
}
}
if (k==2){
if (y0==y) {
remove();
}
if (y0
for (n=y0;n<=y-1 ;n++ ) {
if (grid[i][n]!=0) {
k=0;
break;
}
if(grid[i][n]==0 && n==y-1) {
remove();
}
}
}
if (y0>y) {
for (n=y0;n>=y+1 ;n--) {
if (grid[i][n]!=0) {
k=0;
break;
}
if(grid[i][n]==0 && n==y+1) {
remove();
}
}
}
}
}
}
}
public void linePassOne(){
if (y0>j){ //第一按钮同行空按钮在左边
for (i=y0-1;i>=j ;i-- ){ //判断第一按钮同左侧空按钮之间有没按钮
if (grid[x0][i]!=0) {
k=0;
break;
}
else { k=2; } //K=2说明通过了第二次验证
}
}
if (y0
for (i=y0+1;i<=j ;i++){
if (grid[x0][i]!=0) {
k=0;
break;
}
else{ k=2; }
}
}
}
public void rowPassOne(){
if (x0>i) {
for (j=x0-1;j>=i ;j-- ) {
if (grid[j][y0]!=0) {
k=0;
break;
}
else { k=2; }
}
}
if (x0
for (j=x0+1;j<=i ;j++ ) {
if (grid[j][y0]!=0) {
k=0;
break;
}
else { k=2; }
}
}
}
public void remove(){
firstButton.setVisible(false);
secondButton.setVisible(false);
fraction();
pressInformation=false;
k=0;
grid[x0][y0]=0;
grid[x][y]=0;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==newlyButton){
int grid[][] = new int[8][7];
this.grid = grid;
randomBuild();
mainFrame.setVisible(false);
pressInformation=false;
init();
}
if(e.getSource()==exitButton)
System.exit(0);
if(e.getSource()==resetButton)
reload();
for(int cols = 0;cols < 6;cols++){
for(int rows = 0;rows < 5;rows++ ){
if(e.getSource()==diamondsButton[cols][rows])
estimateEven(cols+1,rows+1,diamondsButton[cols][rows]);
}
}
}
public static void main(String[] args) {
lianliankan llk = new lianliankan();
llk.randomBuild();
llk.init();
}
}
//old 998 lines
//new 318 lines
更多追问追答
追问
有错误
追答
你要新建java工程 上网搜下java小游戏源码 自己好好看看
追问
好吧,我用的是文本
本回答被提问者和网友采纳
已赞过
已踩过<
你对这个回答的评价是?
评论
收起
-
Java经典最新小游戏简易源代码及特效(上手简单,步骤大全,包学会)50个合集.rar
2021-05-15 10:31:35Java源码包实例源码JAVA开发...Java坦克大战网络对战版源代码.rar Java声音播放程序源代码.rar JAVA实现CLDC与MIDP底层编程的代码.rar Java实现HTTP连接与浏览,Java源码下载.rar Java实现的FTP连接与数据浏览程序.rar -
Java实现简单井字棋小游戏代码实例
2020-08-19 13:21:21主要介绍了Java实现简单井字棋小游戏代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 -
Java桌球小游戏源码及相关素材
2021-12-28 19:09:17包含Java桌球小游戏源码及相关素材 -
Java实现简易版联网坦克对战小游戏(附源码)
2020-08-26 02:44:49主要给大家介绍了关于Java实现简易版联网坦克对战小游戏的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧 -
最简单的JAVA游戏代码
2018-08-08 17:33:44基于Swing的最简单的小游戏框架测试,简单易懂,代码行数少,可基于此代码进行扩展 -
java简易推箱子小游戏
2019-01-26 20:43:16一个简单的java实现推箱子的小游戏,涉及简单swing编程,适合初学者练手 -
java代码-使用java制作雷霆战机小游戏的的源代码
2022-04-03 17:32:03java代码-使用java制作雷霆战机小游戏的的源代码 ——学习参考资料:仅用于个人学习使用! -
java小游戏飞机大战 源代码以及素材
2018-10-15 09:27:45java飞机大战的代码以及相应的各种素材,帮助新手入手java -
java实现简单的扫雷小游戏(源码)
2019-06-19 15:09:15java实现简单的扫雷小游戏 java新手 用于学习 -
拳皇(Java简单的小程序)代码实例
2020-08-26 04:28:59主要介绍了拳皇Java简单小程序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 -
Java五子棋游戏源代码集锦
2019-07-22 13:47:31资源名称:Java五子棋游戏源代码集锦资源目录:【】514]java编写的智能五子棋【】five【】fiveChess【】FiveInARow【】Java五子棋代码【】java实现五子棋【】java编写的一个简单的五子棋程序【】java编的五子棋【】... -
java编写的简单移动方块小游戏代码
2020-09-03 00:51:54主要介绍了java编写的简单移动方块小游戏代码,涉及Java简单图形绘制与事件响应的相关技巧,需要的朋友可以参考下 -
java编程小游戏
2018-12-10 19:31:39一款利用java编写的简易小游戏,将解压后的文件夹和源代码放入一个项目下即可成功运行 -
java版赛车小游戏源代码
2020-12-09 09:00:52模拟双人单机版赛车小游戏,适合初学者,用到的都是基础知识,其中包括给赛车添加图片,添加背景音乐,可以练练手,只是实现简单功能,可以自己再续拓展 -
简单的java小游戏源码-greenfoot-cupcake-counter:在GreenfootIDE中开发的简单平台游戏。源代码来自“Cr
2021-05-23 03:42:03简单的java小游戏源码蛋糕柜台 在Greenfoot IDE中开发的简单平台游戏。 源代码取自《 Creative Greenfood》一书。 我已更新代码以在新的Greenfoot 3上运行。 -
经典java小程序源代码合集.zip
2019-12-15 07:12:09160个项目开发实例,聊天项目,小游戏适和新手学习(项目采用GBK编码)。 import java.util.*; import java.io.*; import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*;... -
简单的java代码--贪食蛇小游戏
2017-12-21 21:02:14ublic static void main(String[] args) { /** * 实现窗口 */ JFrame jframe=new JFrame(); jframe.setSize(900,720); //jframe.setBounds(10, 10, 900, 720);//窗口的位置 和大小 jframe.setResizable(false... -
Java简单实现贪吃蛇经典小游戏(附源代码)
2021-12-03 21:30:47Java简单实现贪吃蛇经典小游戏(附源代码) 老刘 77 人赞同了该文章 在我们学习java的时候,为了提高我们的兴趣,我们经常会使用所学到的知识去做一些小游戏,这篇blog就介绍了一个经典而且好理解的小游戏-...Java简单实现贪吃蛇经典小游戏(附源代码)
77 人赞同了该文章
在我们学习java的时候,为了提高我们的兴趣,我们经常会使用所学到的知识去做一些小游戏,这篇blog就介绍了一个经典而且好理解的小游戏-贪吃蛇。
一、使用知识
- Jframe
- GUI
- 双向链表
- 线程
二、使用工具
- IntelliJ IDEA
- jdk 1.8
三、开发过程
3.1素材准备
首先在开发之前应该准备一些素材,已备用,我主要找了一个图片以及一段优雅的音乐。
3.2 开发过程
3.2.1 创建项目
- 首先进入idea首页 open一个你想放项目的文件夹
- 进入之后右键文件名 new 一个新的Directory——Snake
- 把准备好的素材复制到文件中
- 继续创建目录 src/Sanke
- 选中src Mark Directory as — Souces 把src添加为根目录
3.2.2 页面设计
- 创建java Class 文件 Snake - new - java class SnakeName 接下来的时候会对这个SnakeName.java里面的代码不停完善
首先设置窗口格式
package Sanke; import javax.swing.*; /** * @author Swyee **/ public class SnakeGame extends JFrame { SnakeGame(){ this.setBounds(100, 50, 700, 500);//设置窗口大小 this.setLayout(null);//更改layout 以便添加组件 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭窗口的状态 this.setResizable(false);//窗口不可以改变大小 this.setVisible(true);//设置焦点状态为true } public static void main(String[] args) { new SnakeGame(); } }
- 继续创建新的文件 SnakeGrid
package Sanke; import java.awt.*; /** * @author Swyee **/ public class SnakeGrid extends Panel { SnakeGrid(){ this.setBounds(0, 0, 700, 400); this.setBackground(Color.black);设置背景颜色 } }
- 将页面引用到SnakeGame.java中
package Sanke; import javax.swing.*; /** * @author Swyee **/ public class SnakeGame extends JFrame { SnakeGrid snakeGrid= new SnakeGrid(); SnakeGame(){ this.setBounds(100, 50, 700, 500);//设置窗口大小 this.setLayout(null);//更改layout 以便添加组件 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭窗口的状态 this.setResizable(false);//窗口不可以改变大小 this.add(snakeGrid); this.setVisible(true);//设置焦点状态为true } public static void main(String[] args) { new SnakeGame(); } }
运行样式
- 设置背景图片 背景音乐
在SnakeGrid.java中增加Music方法 设置画笔 绘图
package Sanke; import java.applet.Applet; import java.applet.AudioClip; import java.awt.*; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.JPanel; /** * @author Swyee **/ public class SnakeGrid extends JPanel { ImageIcon image = new ImageIcon("Snake/sky.jpg");//图片文件地址 File f= new File("Snake/music.wav");//音乐文件地址 SnakeGrid(){ this.setBounds(0, 0, 700, 400); this.setBackground(Color.black); } /** * 设置画笔 * @param g */ @Override public void paint(Graphics g) { super.paint(g); image.paintIcon(this, g, 0, 0); //设置背景图片 } //读取音乐文件 void Music(){ try { URI uri = f.toURI(); URL url = uri.toURL(); AudioClip aau= Applet.newAudioClip(url); aau.loop(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
在SnakeName中调用
package Sanke; import javax.swing.*; /** * @author Swyee **/ public class SnakeGame extends JFrame { SnakeGrid snakeGrid= new SnakeGrid(); SnakeGame(){ this.setBounds(100, 50, 700, 500);//设置窗口大小 this.setLayout(null);//更改layout 以便添加组件 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭窗口的状态 this.setResizable(false);//窗口不可以改变大小 this.add(snakeGrid); //设置焦点 snakeGrid.setFocusable(true); snakeGrid.requestFocus(); snakeGrid.Music();//调用打开音乐的方法 this.setVisible(true);//设置焦点状态为true } public static void main(String[] args) { new SnakeGame(); } }
呈现
3.23 画蛇
蛇的身体将会有双向链表组成,双向链表能记录一个节点的上一个节点和下一个节点。蛇的移动其实就是节点的变化,从而达到一种移动的视觉。
- 新建java Snake 创建节点
package Sanke; import java.awt.Graphics; public class Snake { public static final int span=20;//间距 public static final String up="u"; public static final String down="d"; public static final String left="l"; public static final String right="r"; class Node{ int row; int col; String dir;//方向 Node next; Node pre; Node(int row,int col,String dir){ this.row = row; this.col = col; this.dir = dir; } public void draw(Graphics g) { g.fillOval(col*span, row*span, span,span); } } }
- 画蛇
在snake里面增加draw()方法
/* 把蛇画出来 */ public void draw(Graphics g) { g.setColor(Color.yellow); for(Node n=head;n!=null;n=n.next){ n.draw(g); g.setColor(Color.green); } }
在SnakeGrid.java中创建蛇
Snake snake = new Snake();//创建蛇
并在paint中调用snake.draw(g);
/** * 设置画笔 * @param g */ @Override public void paint(Graphics g) { super.paint(g); image.paintIcon(this, g, 0, 0); //设置背景图片 snake.draw(g); }
- 控制蛇的移动
在snake中增加键盘调用的方法:
/* 调用键盘的上下左右键 head.dir记录现在操作的是什么按钮,从而更改蛇的状态 向上移送时,下键失效,其他四个方向也是如此判断 */ public void keyboard(KeyEvent e) { switch(e.getKeyCode()){ case KeyEvent.VK_UP: if(head.dir.equals(down)){ break; } head.dir=up; break; case KeyEvent.VK_DOWN: if(head.dir.equals(up)){ break; } head.dir=down; break; case KeyEvent.VK_LEFT: if(head.dir.equals(right)){ break; } head.dir=left; break; case KeyEvent.VK_RIGHT: if(head.dir.equals(left)){ break; } head.dir=right; break; default: break; } }
增加头部的方法
/* 增加头部 不管移动哪个方向都是在相应位置增加一个节点 */ public void addHead(){ Node node = null; switch (head.dir){ case "l": node = new Node(head.row,head.col-1,head.dir); break; case "r": 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 "d": node = new Node(head.row+1,head.col,head.dir); break; default: break; } node.next=head; head.pre=node; head=node; }
删除尾部的方法
/* 删除尾部 删除最后一个节点 */ public void deleteTail(){ tail.pre.next=null; tail=tail.pre; }
增加move的方法
/* 增加move方法 一增一减,实现蛇的移动 */ public void move() { addHead(); deleteTail(); }
在SnakeGrid中创建一个线程类,用来执行蛇的移动方法
class SnakeThread extends Thread{ @Override public void run() { while (true){ try { Thread.sleep(300);//沉睡300ms 用来控制蛇的移动速度 } catch (InterruptedException e) { e.printStackTrace(); } repaint();//每次沉睡完之后都执行一下repaint()方法,重新绘画 } }
print方法中调用remove 在SnakeGrid()创建键盘监听事件:
package Sanke; import java.applet.Applet; import java.applet.AudioClip; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.JPanel; /** * @author Swyee **/ public class SnakeGrid extends JPanel { Snake snake = new Snake();//创建蛇 ImageIcon image = new ImageIcon("Snake/sky.jpg");//图片文件地址 File f= new File("Snake/music.wav");//音乐文件地址 SnakeThread snakeThread = new SnakeThread(); SnakeGrid(){ this.setBounds(0, 0, 700, 400); this.setBackground(Color.black); snakeThread.start(); this.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { snake.keyboard(e); } }); } /** * 设置画笔 * @param g */ @Override public void paint(Graphics g) { super.paint(g); image.paintIcon(this, g, 0, 0); //设置背景图片 snake.move();//蛇移动 snake.draw(g); } //读取音乐文件 void Music(){ try { URI uri = f.toURI(); URL url = uri.toURL(); AudioClip aau= Applet.newAudioClip(url); aau.loop(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } class SnakeThread extends Thread{ @Override public void run() { while (true){ try { Thread.sleep(300);//沉睡300ms 用来控制蛇的移动速度 } catch (InterruptedException e) { e.printStackTrace(); } repaint();//每次沉睡完之后都执行一下repaint()方法,重新绘画 } } } }
执行main方法可以看到可以通过键盘进行控制移动了
3.24创建蛇的食物
增加食物的实例 以及画食物的方法 反映食物坐标的方法 新建Food.java
package Sanke; import java.awt.*; public class Food { int row; int col; Food(){ row = 10;//创建食物的大小 col =10; } public void repearShow(){ row = (int)(Math.random()*18);//生成随机数 乘以食物的大小可以得到坐标 col = (int)(Math.random()*32); } public void draw(Graphics g) {//把食物画出来 g.setColor(Color.red); g.fillRect(col*20, row*20, 20, 20);//表示坐标 } public Rectangle getCoordinates(){ return new Rectangle(col*20,row*20,20,20);//获得食物的坐标 } }
修改Snake.java 增加判断蛇头位置的方法,修改午无参构造方法,改为有参构造,把food添加进来 修改move方法
package Sanke; import java.awt.*; import java.awt.event.KeyEvent; /** * @author Swyee */ public class Snake { public static final int span=20;//间距 public static final String up="u"; public static final String down="d"; public static final String left="l"; public static final String right="r"; Node body;//蛇的身体 Node head;//蛇的头部 Node tail;//蛇的头部 Food food; Snake(Food food){ body = new Node(5,20,left); head = body; tail = body; this.food=food; } class Node{ int row; int col; String dir;//方向 Node next; Node pre; Node(int row,int col,String dir){ this.row = row; this.col = col; this.dir = dir; } public void draw(Graphics g) { g.fillOval(col*span, row*span, span,span);//坐标 } } /* 把蛇画出来 */ public void draw(Graphics g) { g.setColor(Color.yellow); for(Node n=head;n!=null;n=n.next){ n.draw(g); g.setColor(Color.green); } } /* 调用键盘的上下左右键 head.dir记录现在操作的是什么按钮,从而更改蛇的状态 向上移送时,下键失效,其他四个方向也是如此判断 */ public void keyboard(KeyEvent e) { switch(e.getKeyCode()){ case KeyEvent.VK_UP: if(head.dir.equals(down)){ break; } head.dir=up; break; case KeyEvent.VK_DOWN: if(head.dir.equals(up)){ break; } head.dir=down; break; case KeyEvent.VK_LEFT: if(head.dir.equals(right)){ break; } head.dir=left; break; case KeyEvent.VK_RIGHT: if(head.dir.equals(left)){ break; } head.dir=right; break; default: break; } } /* 增加头部 */ public void addHead(){ Node node = null; switch (head.dir){ case "l": node = new Node(head.row,head.col-1,head.dir); break; case "r": 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 "d": node = new Node(head.row+1,head.col,head.dir); break; default: break; } node.next=head; head.pre=node; head=node; } /* 删除尾部 */ public void deleteTail(){ tail.pre.next=null; tail=tail.pre; } /* 增加move方法 */ public void move() { addHead(); if(this.getSnakeRectangle().intersects(food.getCoordinates())){//当蛇头与食物重合的时候 蛇吃食物 食物刷新,不再删除尾巴,达到一种蛇增长的要求 food.repearShow(); }else{ deleteTail(); } } public Rectangle getSnakeRectangle(){//获取蛇头的坐标 return new Rectangle(head.col*span,head.row*span,span,span); } }
在修改snakegrid.java 贪吃蛇的功能就基本实现了
Food food = new Food(); Snake snake = new Snake(food);//创建蛇 ImageIcon image = new ImageIcon("Snake/sky.jpg");//图片文件地址 File f= new File("Snake/music.wav");//音乐文件地址 SnakeThread snakeThread = new SnakeThread();
@Override public void paint(Graphics g) { super.paint(g); image.paintIcon(this, g, 0, 0); //设置背景图片 snake.move();//蛇移动 snake.draw(g); food.draw(g); }
3.2.5增加蛇的存活状态
在Snake中增加蛇的存活状态,每一次移动都判断下是否存活,修改SnakeGrid的线程,执行时进行判断是否存活
public void DeadOrLive(){//超出边框范围 蛇头撞到身体 游戏结束 if(head.row<0 || head.row>rows-1 || head.col<0 ||head.col>cols){ islive=false; } for(Node n=head.next;n!=null;n=n.next){ if(n.col==head.col && n.row==head.row){ islive=false; } } }
public void move() { addHead(); if(this.getSnakeRectangle().intersects(food.getCoordinates())){//当蛇头与食物重合的时候 蛇吃食物 食物刷新,不再删除尾巴,达到一种蛇增长的要求 food.repearShow(); }else{ deleteTail(); } DeadOrLive();//每移动一步都要判断一下是否存活 }
class SnakeThread extends Thread{ boolean flag = true; @Override public void run() { while (Snake.islive && flag) { try { Thread.sleep(300); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (Snake.islive ) { repaint(); } } if (!flag == false) { JOptionPane.showMessageDialog(SnakeGrid.this, "游戏结束"); } }
3.2.6 增加按钮
- 最后的时候,给这个小游戏增加几个按钮,用来实现暂停开始
新建Button.java
package Sanke; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Button extends JPanel{ public static boolean isMove=true;//表示运行状态 SnakeGrid snakeGrid; Button(SnakeGrid snakeGrid){ this.snakeGrid=snakeGrid; this.setBounds(0, 400, 700, 100); JButton jb1 = new JButton("暂停游戏"); JButton jb2 = new JButton("继续游戏"); JButton jb3 = new JButton("重新游戏"); this.add(jb1); this.add(jb2); this.add(jb3); jb1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { isMove=false; } }); jb2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { isMove=true; snakeGrid.setFocusable(true); snakeGrid.requestFocus(); } }); jb3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) {//重新创建蛇等 重新开始游戏 snakeGrid.snakeThread.stopThread(); Food food = new Food(); snakeGrid.food=food; snakeGrid.snake=new Snake(food); Snake.islive=true; isMove=true; SnakeGrid.SnakeThread st = snakeGrid.new SnakeThread(); snakeGrid.snakeThread=st; st.start(); snakeGrid.setFocusable(true); snakeGrid.requestFocus(); } }); } }
再修改SnakeGrid中的thread
package Sanke; import java.applet.Applet; import java.applet.AudioClip; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.JPanel; /** * @author Swyee **/ public class SnakeGrid extends JPanel { Food food = new Food(); Snake snake = new Snake(food);//创建蛇 ImageIcon image = new ImageIcon("Snake/sky.jpg");//图片文件地址 File f= new File("Snake/music.wav");//音乐文件地址 SnakeThread snakeThread = new SnakeThread(); SnakeGrid(){ this.setBounds(0, 0, 700, 400); this.setBackground(Color.black); snakeThread.start(); this.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { snake.keyboard(e); } }); } /** * 设置画笔 * @param g */ @Override public void paint(Graphics g) { super.paint(g); image.paintIcon(this, g, 0, 0); //设置背景图片 snake.move();//蛇移动 snake.draw(g); food.draw(g); } //读取音乐文件 void Music(){ try { URI uri = f.toURI(); URL url = uri.toURL(); AudioClip aau= Applet.newAudioClip(url); aau.loop(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } class SnakeThread extends Thread{ boolean flag = true; @Override public void run() { while(Snake.islive &&flag){ try { Thread.sleep(300); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(Snake.islive&& Button.isMove){ repaint(); } } if(!flag==false){ JOptionPane.showMessageDialog(SnakeGrid.this, "游戏结束"); } } public void stopThread(){ flag=false; } } }
在主页面中把按钮添加上去
package Sanke; import javax.swing.*; /** * @author Swyee **/ public class SnakeGame extends JFrame { SnakeGrid snakeGrid= new SnakeGrid(); Button button = new Button(snakeGrid); SnakeGame(){ this.setBounds(100, 50, 700, 500);//设置窗口大小 this.setLayout(null);//更改layout 以便添加组件 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭窗口的状态 this.setResizable(false);//窗口不可以改变大小 this.add(snakeGrid); this.add(button); //设置焦点 snakeGrid.setFocusable(true); snakeGrid.requestFocus(); snakeGrid.Music();//调用打开音乐的方法 this.setVisible(true);//设置焦点状态为true } public static void main(String[] args) { new SnakeGame(); } }
到这里这个小游戏就全部做完了,当然也可以在其基础上增加其他功能
也可以把这个小游戏打成jar包的形式进行运行,将打好的jar包和资源文件放在同一个目录下,即可正常运行访问
四、打jar包