Java贪吃蛇,请大虾指教啊,我花较长时间缩减代码,如有什么还觉得不清楚,我的QQ172147501,谢谢了,实在不懂了。。。。。。。。。。。。。。。。。
package javaprogram;
import。。。。略-----第一个类:用于定义游戏的格子,在第三个类里共添加1600个
public class GameButton extends JButton{
public int flag;//1为身体 0为格子 -1为食物
public JButton fg;//游戏格子
public GameButton(){
this.flag=0;//格子
fg=new JButton();
}
}
package javaprogram;
import 。。。略-----第二个类:用于存放蛇的身体(身体由第一个类组成)、身体格子的每个x,y坐标
public class Bodyarrary extends JButton{
public int s_x;//蛇身体格子的x坐标
public int s_y;//蛇身体格子的y坐标
public GameButton bodyarrary=new GameButton();//用于存放蛇的身体
//一下代码有无均错
//public Bodyarrary(){
// bodyarrary=new GameButton();
//}
public final void setpox(int x,int y,GameButton gb){
this.s_x=x;
this.s_y=y;
//bodyarrary=new GameButton();
this.bodyarrary=gb;
}
}
package javaprogram;
import 。。。。略----第三个类:定义游戏框架
class MyFrame extends JFrame implements ActionListener,KeyListener{//,MouseListener{
private JPanel gamepanel=new JPanel();//格子面板-----添加蛇的活动区域(由1600个类一对象组成
private JPanel buttonpanel=new JPanel();//按钮面板----添加开始、暂停按钮
private JButton start=new JButton("开始");//开始按钮
private JButton pause=new JButton("暂停");//暂停按钮
private GameButton[][]fg;//存储1600个格子
private Bodyarrary[] bodyarrary=new Bodyarrary[100];//用于存放蛇的身体,最长为100
private static int body_length=0;
public MyFrame(String name){
super(name);
initgui();
}
public void initgui(){
BorderLayout blayout=new BorderLayout();
this.setLayout(blayout);//关联布局管理器
//添加两个面板
this.add(gamepanel,blayout.CENTER);//格子面板
this.add(buttonpanel,blayout.NORTH);//按钮面板
GridLayout glayout=new GridLayout(40,40);//为gamepanel面板设置GridLayout()布局管理器
gamepanel.setLayout(glayout);
gamepanel.setSize(400,400);//设置gamepanel面板的大小
addplates(gamepanel);//这个函数用于添加1600个格子
gamepanel.setBorder(new LineBorder(new Color(102,102,255),2,true));
buttonpanel.setLayout(new FlowLayout());//为buttonpanel面板设置FlowLayout()布局管理器
buttonpanel.add(start);
buttonpanel.add(pause);
setResizable(false);
start.addActionListener(this);
pause.addActionListener(this);
this.addKeyListener(this);
}
public void addplates(JPanel gamepanel){
fg=new GameButton[40][40];//40行40列
for(int i=0;i<40;i++){
for(int j=0;j<40;j++){
fg[i][j]=new GameButton();
fg[i][j].setSize(10,10);
fg[i][j].setIcon(new ImageIcon("E:\bg.jpg"));
gamepanel.add(fg[i][j]);
}
}
}
//以下函数初始化蛇,长度为5,
public void initsnake(){
for(int i=0;i<=4;i++){
fg[10][10+i].setIcon(new ImageIcon("E:\\body.jpg"));//改变原来的按钮图标,且为body.jpg
fg[10][10+i].flag=1;//标注为在该位置有蛇的身体 *1身体 0背景格子 -1食物*
//问题就是这行代码,有了后蛇的身体就只能初始化一格
bodyarrary[body_length++].get_body_state(10,10+i,fg[10][10+i]);//存储初始化身体格子的x,y及身体
}
//main入口类
public class JavaProgram{
public static void main(String[] args) {
MyFrame myframe=new MyFrame("TP 的Java程序......");
myframe.setVisible(true);
myframe.setSize(600,500);
myframe.initsnake();//添加初始化蛇函数
myframe.initfood();//添加初始化实物类
myframe.setFocusable(true);
}
}