1. 求一個(貪吃蛇)的java小程序,要完整的,可運行的,最好是有文檔的!!!
看看吧,停不錯的。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
//Main Class
public class GreedSnake extends KeyAdapter{
JFrame mainFrame;
Canvas paintCanvas;
JLabel labelScore;//計分牌
SnakeModel snakeModel=null;// 蛇
public static final int DEFAULT_WIDTH=500;
public static final int DEFAULT_HEIGHT=300;
public static final int nodeWidth=10;
public static final int nodeHeight=10;
//GreedSnake():初始化游戲界面
public GreedSnake(){
//設置界面元素
mainFrame=new JFrame("貪吃蛇游戲");
Container cp=mainFrame.getContentPane();
labelScore=new JLabel("所得分數為:",JLabel.CENTER);
cp.add(labelScore,BorderLayout.NORTH);
paintCanvas=new Canvas();
paintCanvas.setSize(DEFAULT_WIDTH+1,DEFAULT_HEIGHT+1);
paintCanvas.addKeyListener(this);
cp.add(paintCanvas,BorderLayout.CENTER);
JPanel panelButtom=new JPanel();
panelButtom.setLayout(new BorderLayout());
JLabel labelHelp;// 幫助信息
labelHelp=new JLabel("按 PageUP 或 PageDown 鍵改變速度",JLabel.CENTER);
panelButtom.add(labelHelp,BorderLayout.NORTH);
labelHelp=new JLabel("按 Enter 或 S 鍵重新開始游戲",JLabel.CENTER);
panelButtom.add(labelHelp,BorderLayout.CENTER);
labelHelp=new JLabel("按 SPACE 鍵或 P 鍵暫停游戲",JLabel.CENTER);
panelButtom.add(labelHelp,BorderLayout.SOUTH);
cp.add(panelButtom,BorderLayout.SOUTH);
mainFrame.addKeyListener(this);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
begin();
}
//keyPressed():按鍵檢測
public void keyPressed(KeyEvent e){
int keyCode=e.getKeyCode();
if(snakeModel.running)
switch(keyCode){
case KeyEvent.VK_UP:
snakeModel.changeDirection(SnakeModel.UP);
break;
case KeyEvent.VK_DOWN:
snakeModel.changeDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_LEFT:
snakeModel.changeDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_RIGHT:
snakeModel.changeDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_PAGE_UP:
snakeModel.speedUp();// 加速
break;
case KeyEvent.VK_SUBTRACT:
case KeyEvent.VK_PAGE_DOWN:
snakeModel.speedDown();// 減速
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
snakeModel.changePauseState();// 暫停或繼續
break;
default:
}
//重新開始
if(keyCode==KeyEvent.VK_S || keyCode==KeyEvent.VK_ENTER){
snakeModel.running=false;
begin();
}
}
//repaint():繪制游戲界面(包括蛇和食物)
void repaint(){
Graphics g=paintCanvas.getGraphics();
//draw background
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0,0,DEFAULT_WIDTH,DEFAULT_HEIGHT);
//draw the snake
g.setColor(Color.BLACK);
LinkedList na=snakeModel.nodeArray;
Iterator it=na.iterator();
while(it.hasNext()){
Node n=(Node)it.next();
drawNode(g,n);
}
// draw the food
g.setColor(Color.RED);
Node n=snakeModel.food;
drawNode(g,n);
updateScore();
}
//drawNode():繪畫某一結點(蛇身或食物)
private void drawNode(Graphics g,Node n){
g.fillRect(n.x*nodeWidth,n.y*nodeHeight,nodeWidth-1,nodeHeight-1);
}
//updateScore():改變計分牌
public void updateScore(){
String s="所得分數為: "+snakeModel.score;
labelScore.setText(s);
}
//begin():游戲開始,放置貪吃蛇
void begin(){
if(snakeModel==null||!snakeModel.running){
snakeModel=new SnakeModel(this,DEFAULT_WIDTH/nodeWidth,
DEFAULT_HEIGHT/nodeHeight);
(new Thread(snakeModel)).start();
}
}
//main():主函數
public static void main(String[] args){
GreedSnake gs=new GreedSnake();
}
}
//Node:結點類
class Node{
int x;
int y;
Node(int x,int y){
this.x=x;
this.y=y;
}
}
//SnakeModel:貪吃蛇模型
class SnakeModel implements Runnable{
GreedSnake gs;
boolean[][] matrix;// 界面數據保存在數組里
LinkedList nodeArray=new LinkedList();
Node food;
int maxX;//最大寬度
int maxY;//最大長度
int direction=2;//方向
boolean running=false;
int timeInterval=200;// 間隔時間(速度)
double speedChangeRate=0.75;// 速度改變程度
boolean paused=false;// 游戲狀態
int score=0;
int countMove=0;
// UP和DOWN是偶數,RIGHT和LEFT是奇數
public static final int UP=2;
public static final int DOWN=4;
public static final int LEFT=1;
public static final int RIGHT=3;
//GreedModel():初始化界面
public SnakeModel(GreedSnake gs,int maxX,int maxY){
this.gs=gs;
this.maxX=maxX;
this.maxY=maxY;
matrix=new boolean[maxX][];
for(int i=0;i<maxX;++i){
matrix[i]=new boolean[maxY];
Arrays.fill(matrix[i],false);// 沒有蛇和食物的地區置false
}
//初始化貪吃蛇
int initArrayLength=maxX>20 ? 10 : maxX/2;
for(int i=0;i<initArrayLength;++i){
int x=maxX/2+i;
int y=maxY/2;
nodeArray.addLast(new Node(x,y));
matrix[x][y]=true;// 蛇身處置true
}
food=createFood();
matrix[food.x][food.y]=true;// 食物處置true
}
//changeDirection():改變運動方向
public void changeDirection(int newDirection){
if(direction%2!=newDirection%2){// 避免沖突
direction=newDirection;
}
}
//moveOn():貪吃蛇運動函數
public boolean moveOn(){
Node n=(Node)nodeArray.getFirst();
int x=n.x;
int y=n.y;
switch(direction){
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
if((0<=x&&x<maxX)&&(0<=y&&y<maxY)){
if(matrix[x][y]){// 吃到食物或者撞到身體
if(x==food.x&&y==food.y){// 吃到食物
nodeArray.addFirst(food);// 在頭部加上一結點
//計分規則與移動長度和速度有關
int scoreGet=(10000-200*countMove)/timeInterval;
score+=scoreGet>0 ? scoreGet : 10;
countMove=0;
food=createFood();
matrix[food.x][food.y]=true;
return true;
}
else return false;// 撞到身體
}
else{//什麼都沒有碰到
nodeArray.addFirst(new Node(x,y));// 加上頭部
matrix[x][y]=true;
n=(Node)nodeArray.removeLast();// 去掉尾部
matrix[n.x][n.y]=false;
countMove++;
return true;
}
}
return false;//越界(撞到牆壁)
}
//run():貪吃蛇運動線程
public void run(){
running=true;
while(running){
try{
Thread.sleep(timeInterval);
}
catch(Exception e){
break;
}
if(!paused){
if(moveOn()){// 未結束
gs.repaint();
}
else{//游戲結束
JOptionPane.showMessageDialog(null,"GAME OVER",
"Game Over",JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
running=false;
}
//createFood():生成食物及放置地點
private Node createFood(){
int x=0;
int y=0;
do{
Random r=new Random();
x=r.nextInt(maxX);
y=r.nextInt(maxY);
}
while(matrix[x][y]);
return new Node(x,y);
}
//speedUp():加快蛇運動速度
public void speedUp(){
timeInterval*=speedChangeRate;
}
//speedDown():放慢蛇運動速度
public void speedDown(){
timeInterval/=speedChangeRate;
}
//changePauseState(): 改變游戲狀態(暫停或繼續)
public void changePauseState(){
paused=!paused;
}
}
2. Java 編寫 貪吃蛇游戲的 大體思路是什麼
在畫布上,我們首先需要畫出蛇的頭部,這代表了貪吃蛇游戲的起點。雖然蛇會隨著游戲的進行而變長,但它的基本構造仍然是由一系列坐標點組成的,我通常使用LinkedList來存儲這些坐標點,因為它的插入和刪除操作更為高效。這里的每個坐標點實際上代表了蛇的一個「塊」。
為了讓蛇移動起來,我們需要一個線程來調用move()方法,這個方法將負責蛇的每一次移動。同時,我們還需要確保蛇的移動具有方向性。為了實現這一點,我們可以編寫一個方法,通過接收一個方向參數來控制蛇的移動方向,同時還需要一個機制來禁止蛇在移動時改變與當前方向相反的方向。比如,如果當前蛇的方向是向上移動,那麼它就不能向下移動。
當蛇與邊界接觸時,游戲應當結束。因此,我們需要在蛇移動的過程中檢查它是否越過了邊界,如果越界則游戲結束。接下來是食物的出現,食物的位置需要隨機生成,但必須確保它不會出現在邊界之外。當蛇吃到食物時,需要有一個方法來處理這一事件,比如增加蛇的長度,並在適當的位置生成新的食物。
此外,如果蛇與自己的身體發生碰撞,游戲同樣需要結束。這可以通過遍歷蛇的各個部分來檢查是否有重疊來實現。如果檢測到重疊,則游戲結束。這樣的邏輯構成了貪吃蛇游戲的基本框架,後續則可以添加更多細節,如得分系統、不同難度級別的設定等。
通過上述步驟,我們可以大致構建出一個簡單的貪吃蛇游戲。當然,這只是一個起點,實際開發中還需要考慮許多細節問題,比如用戶界面的美化、游戲的優化等。但以上步驟提供了一個清晰的開發思路,對於初學者來說是一個很好的起點。
3. 用JAVA編一個小的貪吃蛇游戲 (要求如下) 求JAVA高手
不合意的自己去修改
import java.awt.*;
import java.awt.event.*;
public class GreedSnake //主類
{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyWindow();
}
}
class MyPanel extends Panel implements KeyListener,Runnable//自定義面板類,繼承了鍵盤和線程介面
{
Button snake[]; //定義蛇按鈕
int shu=0; //蛇的節數
int food[]; //食物數組
boolean result=true; //判定結果是輸 還是贏
Thread thread; //定義線程
static int weix,weiy; //食物位置
boolean t=true; //判定游戲是否結束
int fangxiang=0; //蛇移動方向
int x=0,y=0; //蛇頭位置
MyPanel()
{
setLayout(null);
snake=new Button[20];
food=new int [20];
thread=new Thread(this);
for(int j=0;j<20;j++)
{
food[j]=(int)(Math.random()*99);//定義20個隨機食物
}
weix=(int)(food[0]*0.1)*60; //十位*60為橫坐標
weiy=(int)(food[0]%10)*40; //個位*40為縱坐標
for(int i=0;i<20;i++)
{
snake[i]=new Button();
}
add(snake[0]);
snake[0].setBackground(Color.black);
snake[0].addKeyListener(this); //為蛇頭添加鍵盤監視器
snake[0].setBounds(0,0,10,10);
setBackground(Color.cyan);
}
public void run() //接收線程
{
while(t)
{
if(fangxiang==0)//向右
{
try
{
x+=10;
snake[0].setLocation(x, y);//設置蛇頭位置
if(x==weix&&y==weiy) //吃到食物
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint(); //重繪下一個食物
add(snake[shu]); //增加蛇節數和位置
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100); //睡眠100ms
}
catch(Exception e){}
}
else if(fangxiang==1)//向左
{
try
{
x-=10;
snake[0].setLocation(x, y);
if(x==weix&&y==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
else if(fangxiang==2)//向上
{
try
{
y-=10;
snake[0].setLocation(x, y);
if(x==weix&&y==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
else if(fangxiang==3)//向下
{
try
{
y+=10;
snake[0].setLocation(x, y);
if(x==weix&&y==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
int num1=shu;
while(num1>1)//判斷是否咬自己的尾巴
{
if(snake[num1].getBounds().x==snake[0].getBounds().x&&snake[num1].getBounds().y==snake[0].getBounds().y)
{
t=false;
result=false;
repaint();
}
num1--;
}
if(x<0||x>=this.getWidth()||y<0||y>=this.getHeight())//判斷是否撞牆
{
t=false;
result=false;
repaint();
}
int num=shu;
while(num>0) //設置蛇節位置
{
snake[num].setBounds(snake[num-1].getBounds());
num--;
}
if(shu==15) //如果蛇節數等於15則勝利
{
t=false;
result=true;
repaint();
}
}
}
public void keyPressed(KeyEvent e) //按下鍵盤方向鍵
{
if(e.getKeyCode()==KeyEvent.VK_RIGHT)//右鍵
{
if(fangxiang!=1)//如果先前方向不為左
fangxiang=0;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{ if(fangxiang!=0)
fangxiang=1;
}
else if(e.getKeyCode()==KeyEvent.VK_UP)
{ if(fangxiang!=3)
fangxiang=2;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{ if(fangxiang!=2)
fangxiang=3;
}
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void paint(Graphics g) //在面板上繪圖
{
int x1=this.getWidth()-1;
int y1=this.getHeight()-1;
g.setColor(Color.red);
g.fillOval(weix, weiy, 10, 10);//食物
g.drawRect(0, 0, x1, y1); //牆
if(t==false&&result==false)
g.drawString("GAME OVER!", 250, 200);//輸出遊戲失敗
else if(t==false&&result==true)
g.drawString("YOU WIN!", 250, 200);//輸出遊戲成功
}
}
class MyWindow extends Frame implements ActionListener//自定義窗口類
{
MyPanel my;
Button btn;
Panel panel;
MyWindow()
{
super("GreedSnake");
my=new MyPanel();
btn=new Button("begin");
panel=new Panel();
btn.addActionListener(this);
panel.add(new Label("begin後請按Tab鍵選定蛇"));
panel.add(btn);
panel.add(new Label("按上下左右鍵控制蛇行動"));
add(panel,BorderLayout.NORTH);
add(my,BorderLayout.CENTER);
setBounds(100,100,610,500);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)//按下begin按鈕
{
if(e.getSource()==btn)
{
try
{
my.thread.start(); //開始線程
my.validate();
}
catch(Exception ee){}
}
}
}
4. 誰會用java編寫「貪吃蛇」小游戲
汗 要程序怎麼這么點分啊 哭了
呵呵 不過你還是挺幸運 給你吧
連連看的代碼(基本演算法)加了部分注釋
import java.awt.*;
import java.awt.event.*;
public class lianliankan implements ActionListener
{
static String s="no"; //用來紀錄點擊按鈕的信息
int x0=0,y0=0,x=0,y=0,n1=0,n2=0; //用來紀錄按鈕的位置信息
Frame f,f1;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10; //用比較笨的方法添加了
Button b11,b12,b13,b14,b15,b16,b17,b18; //30個按鈕來實現游戲界面
Button b19,b20,b21,b22,b23,b24,b25; //可以用數組實現,這是本人
Button b26,b27,b28,b29,b30,bc; //學java時,入門的聯系,所以
Button b,ba,br,bt1,bt2; //有些東西很業余!!嘻嘻
Panel p1,p2,p3;
TextField t; //用來顯示一些隨機信息,方法是下面的guli().
Label l;
int d[][]={ //用來和界面的按鈕建立映射關系
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0}
};
public static void main(String[] args)
{
lianliankan t=new lianliankan();
t.suiji();
t.go();
}
public void actionPerformed(ActionEvent e) //再來一次按鈕的響應事件。
{
int d[][]={
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0}
};
this.d=d;
suiji();
f.setVisible(false);
f1.setVisible(false);
s="no";
go();
}
public void go()//初始化界面
{
l=new Label("親愛的玩家,");
f=new Frame("連連看");
t=new TextField();
p2=new Panel();
p1=new Panel();
p3=new Panel();
bc=new Button("退出");
br=new Button("重列");
b=new Button();
b1=new Button(String.valueOf(d[1][1]));
b2=new Button(String.valueOf(d[1][2]));
b3=new Button(String.valueOf(d[1][3]));
b4=new Button(String.valueOf(d[1][4]));
b5=new Button(String.valueOf(d[1][5]));
b6=new Button(String.valueOf(d[2][1]));
b7=new Button(String.valueOf(d[2][2]));
b8=new Button(String.valueOf(d[2][3]));
b9=new Button(String.valueOf(d[2][4]));
b10=new Button(String.valueOf(d[2][5]));
b11=new Button(String.valueOf(d[3][1]));
b12=new Button(String.valueOf(d[3][2]));
b13=new Button(String.valueOf(d[3][3]));
b14=new Button(String.valueOf(d[3][4]));
b15=new Button(String.valueOf(d[3][5]));
b16=new Button(String.valueOf(d[4][1]));
b17=new Button(String.valueOf(d[4][2]));
b18=new Button(String.valueOf(d[4][3]));
b19=new Button(String.valueOf(d[4][4]));
b20=new Button(String.valueOf(d[4][5]));
b21=new Button(String.valueOf(d[5][1]));
b22=new Button(String.valueOf(d[5][2]));
b23=new Button(String.valueOf(d[5][3]));
b24=new Button(String.valueOf(d[5][4]));
b25=new Button(String.valueOf(d[5][5]));
b26=new Button(String.valueOf(d[6][1]));
b27=new Button(String.valueOf(d[6][2]));
b28=new Button(String.valueOf(d[6][3]));
b29=new Button(String.valueOf(d[6][4]));
b30=new Button(String.valueOf(d[6][5]));
p3.setLayout(null);
p1.setSize(250,300);
p2.setSize(100,40);
p3.setSize(300,30);
t.setSize(60,30);
l.setSize(70,30);
p1.setLayout(new GridLayout(6,5));
p1.setBackground(Color.pink);
p1.setLocation(100,100);
p2.setLocation(0,400);
p3.setLocation(50,50);
t.setLocation(230,2);
l.setLocation(150,2);
bc.setLocation(0,40);
br.setLocation(0,100);
f.add(p1);
f.add(p2);
f.add(p3);
p3.add(l);
p3.add(t);
p2.add(bc);
p2.add(br);
p1.add(b1);
p1.add(b2);
p1.add(b3);
p1.add(b4);
p1.add(b5);
p1.add(b6);
p1.add(b7);
p1.add(b8);
p1.add(b9);
p1.add(b10);
p1.add(b11);
p1.add(b12);
p1.add(b13);
p1.add(b14);
p1.add(b15);
p1.add(b16);
p1.add(b17);
p1.add(b18);
p1.add(b19);
p1.add(b20);
p1.add(b21);
p1.add(b22);
p1.add(b23);
p1.add(b24);
p1.add(b25);
p1.add(b26);
p1.add(b27);
p1.add(b28);
p1.add(b29);
p1.add(b30);
f.pack();
f.setBounds(280,100,500,450);
f.setResizable(false);
f.setVisible(true);
bc.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
ex();
}
});
br.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
chonglie();
}
});
b1.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(1,1,b1);
}
});
b2.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(1,2,b2);
}
});
b3.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(1,3,b3);
}
});
b4.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(1,4,b4);
}
});
b5.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(1,5,b5);
}
});
b6.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(2,1,b6);
}
});
b7.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(2,2,b7);
}
});
b8.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(2,3,b8);
}
});
b9.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(2,4,b9);
}
});
b10.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(2,5,b10);
}
});
b11.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(3,1,b11);
}
});
b12.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(3,2,b12);
}
});
b13.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(3,3,b13);
}
});
b14.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(3,4,b14);
}
});
b15.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(3,5,b15);
}
});
b16.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(4,1,b16);
}
});
b17.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(4,2,b17);
}
});
b18.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(4,3,b18);
}
});
b19.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(4,4,b19);
}
});
b20.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(4,5,b20);
}
});
b21.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(5,1,b21);
}
});
b22.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(5,2,b22);
}
});
b23.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(5,3,b23);
}
});
b24.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(5,4,b24);
}
});
b25.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(5,5,b25);
}
});
b26.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(6,1,b26);
}
});
b27.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(6,2,b27);
}
});
b28.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(6,3,b28);
}
});
b29.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(6,4,b29);
}
});
b30.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
wei(6,5,b30);
}
});
}
public void ex() //退出界面,可用diolog來實現有模式的類型,更加符合
{
f1=new Frame("游戲作業");
f1.setLayout(new GridLayout(1,1));
bt1=new Button("確定退出");
bt2=new Button("再來一局");
f1.add(bt1);
f1.add(bt2);
f1.pack();
f1.setBounds(400,250,90,60);
f1.setResizable(false);
f1.show();
f1.setVisible(true);
bt1.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
System.exit(0);
}
});
bt2.addActionListener(this);
}
public void suiji() //產生隨機數,來填充游戲界面對應的數組的各個位置
{
int m,n,k=0,k1,k2,k3;
for(m=1;m<=15;m++)
{
k1=(int)(Math.random()*25+1);
for(n=1;n<=2;n++)
{
k2=(int)(Math.random()*6+1);
k3=(int)(Math.random()*5+1);
while(d[k2][k3]!=0 && k!=30)
{
k2=(int)(Math.random()*6+1);
k3=(int)(Math.random()*5+1);
}
this.d[k2][k3]=k1;
k++;
}
}
}
public void guli() //隨機信息
{
int l=0;
t.setText("");
l=(int)(Math.random()*10);
System.out.println(l);
switch(l)
{
case 1:
t.setText("好!加油!");
break;
case 3:
t.setText("你真棒!");
break;
case 5:
t.setText("加快速度!");
break;
case 6:
t.setText("不錯啊!");
break;
case 8:
t.setText("加油吧!");
break;
case 9:
t.setText("夠聰明!");
break;
default:
break;
}
}
public void chonglie() //重列方法
{
int save[],i,j,n=0,k2,k3,k;
int d[][]={
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0}
};
save=new int[30];
for(n=0;n<30;n++)
save[n]=0; //定義一個數組來保存當前的每個按鈕位置上的信息
n=0;
for(i=0;i<=6;i++)
for(j=0;j<=5;j++)
{
if(this.d[i][j]!=0)
{
save[n]=this.d[i][j];
n++;
}
}
n=n-1;
this.d=d;
while(n>=0) //產生隨機位置,放置按鈕
{
k2=(int)(Math.random()*6+1);
k3=(int)(Math.random()*5+1);
while(d[k2][k3]!=0)
{
k2=(int)(Math.random()*6+1);
k3=(int)(Math.random()*5+1);
}
this.d[k2][k3]=save[n];
n--;
}
f.setVisible(false);
s="no"; //這里一定要將按鈕點擊信息歸為初始
go();
ling();
}
public void ling() //將數組中為零的成員對應的按鈕消去
{ //用按鈕類型的數組實現會簡化得多,
if(d[1][1]==0)
b1.setVisible(false);
if(d[1][2]==0)
b2.setVisible(false);
if(d[1][3]==0)
b3.setVisible(false);
if(d[1][4]==0)
b4.setVisible(false);
if(d[1][5]==0)
b5.setVisible(false);
if(d[2][1]==0)
b6.setVisible(false);
if(d[2][2]==0)
b7.setVisible(false);
if(d[2][3]==0)
b8.setVisible(false);
if(d[2][4]==0)
b9.setVisible(false);
if(d[2][5]==0)
b10.setVisible(false);
if(d[3][1]==0)
b11.setVisible(false);
if(d[3][2]==0)
b12.setVisible(false);
if(d[3][3]==0)
b13.setVisible(false);
if(d[3][4]==0)
b14.setVisible(false);
if(d[3][5]==0)
b15.setVisible(false);
if(d[4][1]==0)
b16.setVisible(false);
if(d[4][2]==0)
b17.setVisible(false);
if(d[4][3]==0)
b18.setVisible(false);
if(d[4][4]==0)
b19.setVisible(false);
if(d[4][5]==0)
b20.setVisible(false);
if(d[5][1]==0)
b21.setVisible(false);
if(d[5][2]==0)
b22.setVisible(false);
if(d[5][3]==0)
b23.setVisible(false);
if(d[5][4]==0)
b24.setVisible(false);
if(d[5][5]==0)
b25.setVisible(false);
if(d[6][1]==0)
b26.setVisible(false);
if(d[6][2]==0)
b27.setVisible(false);
if(d[6][3]==0)
b28.setVisible(false);
if(d[6][4]==0)
b29.setVisible(false);
if(d[6][5]==0)
b30.setVisible(false);
}
public void wei(int w1,int w2,Button bz) //判斷並紀錄每次點擊按鈕的信息
{ //當兩次的按鈕相同才能消去
if((s.trim()).equals("no"))
{
s=b1.getLabel();
x0=w1;
y0=w2;
n1=d[x0][y0];
b=bz;
x=w1;
y=w2;
n2=d[x][y];
ba=bz;
}
else
{
x0=x;
y0=y;
n1=d[x0][y0];
b=ba;
x=w1;
y=w2;
n2=d[x][y];
ba=bz;
if(n1==n2 && ba!=b)
{
xiao();
}
}
}
public void xiao() //這里是整個游戲最重要的部分,就是判斷兩個按鈕在信息
{ //相同的情況下能不能消去。仔細分析,不一條條注釋
int i=0, j=0,n=0,k=0;
if((x0==x &&(y0==y+1||y0==y-1)) || ((x0==x+1||x0==x-1)&&(y0==y))) //相鄰的情況
{
ba.setVisible(false);
b.setVisible(false);
guli();
s="no";
d[x0][y0]=0;
d[x][y]=0;
}
else
{
for (j=0;j<7;j++ ) //兩個按鈕按行分析,看能否消去
{
if (d[x0][j]==0)
{
if (y>j)
{
for (i=y-1;i>=j;i-- )
{
if (d[x][i]!=0)
{
k=0;
break;
}
else
{
k=1;
}
}
if (k==1)
{
if (y0>j)
{
for (i=y0-1;i>=j ;i-- )
{
if (d[x0][i]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
if (y0<j)
{
for (i=y0+1;i<=j ;i++)
{
if (d[x0][i]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
}
}
if (y<j)
{
for (i=y+1;i<=j ;i++ )
{
if (d[x][i]!=0)
{
k=0;
break;
}
else
{
k=1;
}
}
if (k==1)
{
if (y0>j)
{
for (i=y0-1;i>=j ;i-- )
{
if (d[x0][i]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
if (y0<j)
{
for (i=y0+1;i<=j ;i++)
{
if (d[x0][i]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
}
}
if (y==j )
{
if (y0>j)
{
for (i=y0-1;i>=j ;i-- )
{
if (d[x0][i]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
if (y0<j)
{
for (i=y0+1;i<=j ;i++)
{
if (d[x0][i]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
}
}
if (k==2)
{ if (x0==x)
{
b.setVisible(false);
ba.setVisible(false);
guli();
s="no";
k=0;
d[x0][y0]=0;
d[x][y]=0;
}
if (x0<x)
{
for (n=x0;n<=x-1;n++ )
{
if (d[n][j]!=0)
{
k=0;
break;
}
if(d[n][j]==0 && n==x-1)
{
b.setVisible(false);
ba.setVisible(false);
guli();
s="no";
k=0;
d[x0][y0]=0;
d[x][y]=0;
}
}
}
if (x0>x)
{
for (n=x0;n>=x+1 ;n-- )
{
if (d[n][j]!=0)
{
k=0;
break;
}
if(d[n][j]==0 && n==x+1)
{
b.setVisible(false);
ba.setVisible(false);
guli();
s="no";
k=0;
d[x0][y0]=0;
d[x][y]=0;
}
}
}
}
}
for (i=0;i<8;i++ ) //按列分析,看能不能消去
{
if (d[i][y0]==0)
{
if (x>i)
{
for (j=x-1;j>=i ;j-- )
{
if (d[j][y]!=0)
{
k=0;
break;
}
else
{
k=1;
}
}
if (k==1)
{
if (x0>i)
{
for (j=x0-1;j>=i ;j-- )
{
if (d[j][y0]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
if (x0<i)
{
for (j=x0+1;j<=i;j++ )
{
if (d[j][y0]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
}
}
if (x<i)
{
for (j=x+1;j<=i;j++ )
{
if (d[j][y]!=0)
{
k=0;
break;
}
else
{
k=1;
}
}
if (k==1)
{
if (x0>i)
{
for (j=x0-1;j>=i ;j-- )
{
if (d[j][y0]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
if (x0<i)
{
for (j=x0+1;j<=i ;j++ )
{
if (d[j][y0]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
}
}
if (x==i)
{
if (x0>i)
{
for (j=x0-1;j>=i ;j-- )
{
if (d[j][y0]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
if (x0<i)
{
for (j=x0+1;j<=i ;j++ )
{
if (d[j][y0]!=0)
{
k=0;
break;
}
else
{
k=2;
}
}
}
}
}
if (k==2)
{
if (y0==y)
{
b.setVisible(false);
ba.setVisible(false);
guli();
s="no";
k=0;
d[x0][y0]=0;
d[x][y]=0;
}
if (y0<y)
{
for (n=y0;n<=y-1 ;n++ )
{
if (d[i][n]!=0)
{
k=0;
break;
}
if(d[i][n]==0 && n==y-1)
{
b.setVisible(false);
ba.setVisible(false);
guli();
s="no";
k=0;
d[x0][y0]=0;
d[x][y]=0;
}
}
}
if (y0>y)
{
for (n=y0;n>=y+1 ;n--)
{
if (d[i][n]!=0)
{
k=0;
break;
}
if(d[i][n]==0 && n==y+1)
{
b.setVisible(false);
ba.setVisible(false);
guli();
s="no";
k=0;
d[x0][y0]=0;
d[x][y]=0;
}
}
}
}
}
}
}
}
5. Java 編寫貪吃蛇游戲的大體思路是什麼
樓主沒有看到蛇移動的本質,蛇雖然是分成很多塊,但他們還是一個整體,每一塊的移動都和上一塊有關,所以不需要對每一塊都進行判斷。x0dx0a原理:x0dx0a把蛇身體的每一塊看成一個對象(對象存儲該塊的坐標和相關信息),作為節點存儲在線性鏈表中,再設置一個變數標志蛇的方向(通過按鍵可以改變)。一般人都是讓每一個節點等於他指向的下一個節點,並讓頭節點改變位置來實差局現轉彎和移動,這個演算法復雜度太高(O(n)),實際上只要做兩步操作,插入一個頭節點,刪除一個尾節點就可以了,新插入的頭節點位置根據蛇當前的方向決定 用一個數組將蛇頭的行徑記錄下來,然後第二段的下一個方格設置為蛇頭走過的方格,這樣子蛇走過的路徑都是前一段走過的,最後將跟著蛇頭走了,比如x0dx0a蛇身的路徑x0dx0a for(int i=snakeLength-1;i>0;i--){x0dx0arows[i]=rows[i-1];//依次將蛇前面一段走過行的路段賦值給蛇的下一段x0dx0acols[i]=cols[i-1];//依次將蛇前面一段走過列的路段賦值給蛇的下一段x0dx0a}x0dx0afor(int i=1;i 6. 求JAVA貪吃蛇代碼 要能運行有註解的!
import java.awt.*; 7. 哪位能告訴我貪吃蛇游戲的全部代碼
//package main;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class GreedSnake implements KeyListener{
JFrame mainFrame;
Canvas paintCanvas;
JLabel labelScore;
SnakeModel snakeModel = null;
public static final int canvasWidth = 200;
public static final int canvasHeight = 300;
public static final int nodeWidth = 10;
public static final int nodeHeight = 10;
public GreedSnake() {
mainFrame = new JFrame("GreedSnake");
Container cp = mainFrame.getContentPane();
labelScore = new JLabel("Score:");
cp.add(labelScore, BorderLayout.NORTH);
paintCanvas = new Canvas();
paintCanvas.setSize(canvasWidth+1,canvasHeight+1);
paintCanvas.addKeyListener(this);
cp.add(paintCanvas, BorderLayout.CENTER);
JPanel panelButtom = new JPanel();
panelButtom.setLayout(new BorderLayout());
JLabel labelHelp;
labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.NORTH);
labelHelp = new JLabel("ENTER or R or S for start;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.CENTER);
labelHelp = new JLabel("SPACE or P for pause",JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.SOUTH);
cp.add(panelButtom,BorderLayout.SOUTH);
mainFrame.addKeyListener(this);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
begin();
}
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if (snakeModel.running)
switch(keyCode){
case KeyEvent.VK_UP:
snakeModel.changeDirection(SnakeModel.UP);
break;
case KeyEvent.VK_DOWN:
snakeModel.changeDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_LEFT:
snakeModel.changeDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_RIGHT:
snakeModel.changeDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_PAGE_UP:
snakeModel.speedUp();
break;
case KeyEvent.VK_SUBTRACT:
case KeyEvent.VK_PAGE_DOWN:
snakeModel.speedDown();
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
snakeModel.changePauseState();
break;
default:
}
if (keyCode == KeyEvent.VK_R ||
keyCode == KeyEvent.VK_S ||
keyCode == KeyEvent.VK_ENTER){
snakeModel.running = false;
begin();
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
void repaint(){
Graphics g = paintCanvas.getGraphics();
//draw background
g.setColor(Color.WHITE);
g.fillRect(0,0,canvasWidth,canvasHeight);
// draw the snake
g.setColor(Color.BLACK);
LinkedList na = snakeModel.nodeArray;
Iterator it = na.iterator();
while(it.hasNext()){
Node n = (Node)it.next();
drawNode(g,n);
}
// draw the food
g.setColor(Color.RED);
Node n = snakeModel.food;
drawNode(g,n);
updateScore();
}
private void drawNode(Graphics g, Node n){
g.fillRect(n.x*nodeWidth,
n.y*nodeHeight,
nodeWidth-1,
nodeHeight-1);
}
public void updateScore(){
String s = "Score: " + snakeModel.score;
labelScore.setText(s);
}
void begin(){
if (snakeModel == null || !snakeModel.running){
snakeModel = new SnakeModel(this,
canvasWidth/nodeWidth,
canvasHeight/nodeHeight);
(new Thread(snakeModel)).start();
}
}
public static void main(String[] args){
GreedSnake gs = new GreedSnake();
}
}
///////////////////////////////////////////////////
//文件2
///////////////////////////////////////////////////
import java.util.*;
import javax.swing.*;
class SnakeModel implements Runnable{
GreedSnake gs;
boolean[][] matrix;
LinkedList nodeArray = new LinkedList();
Node food;
int maxX;
int maxY;
int direction = 2;
boolean running = false;
int timeInterval = 200;
double speedChangeRate = 0.75;
boolean paused = false;
int score = 0;
int countMove = 0;
// UP and DOWN should be even
// RIGHT and LEFT should be odd
public static final int UP = 2;
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;
public SnakeModel(GreedSnake gs, int maxX, int maxY){
this.gs = gs;
this.maxX = maxX;
this.maxY = maxY;
// initial matirx
matrix = new boolean[maxX][];
for(int i=0; i<maxX; ++i){
matrix[i] = new boolean[maxY];
Arrays.fill(matrix[i],false);
}
// initial the snake
int initArrayLength = maxX > 20 ? 10 : maxX/2;
for(int i = 0; i < initArrayLength; ++i){
int x = maxX/2+i;
int y = maxY/2;
nodeArray.addLast(new Node(x, y));
matrix[x][y] = true;
}
food = createFood();
matrix[food.x][food.y] = true;
}
public void changeDirection(int newDirection){
if (direction % 2 != newDirection % 2){
direction = newDirection;
}
}
public boolean moveOn(){
Node n = (Node)nodeArray.getFirst();
int x = n.x;
int y = n.y;
switch(direction){
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
if ((0 <= x && x < maxX) && (0 <= y && y < maxY)){
if (matrix[x][y]){
if(x == food.x && y == food.y){
nodeArray.addFirst(food);
int scoreGet = (10000 - 200 * countMove) / timeInterval;
score += scoreGet > 0? scoreGet : 10;
countMove = 0;
food = createFood();
matrix[food.x][food.y] = true;
return true;
}
else
return false;
}
else{
nodeArray.addFirst(new Node(x,y));
matrix[x][y] = true;
n = (Node)nodeArray.removeLast();
matrix[n.x][n.y] = false;
countMove++;
return true;
}
}
return false;
}
public void run(){
running = true;
while (running){
try{
Thread.sleep(timeInterval);
}
catch(Exception e){
break;
}
if(!paused){
if (moveOn()){
gs.repaint();
}
else{
JOptionPane.showMessageDialog(
null,
"you failed",
"Game Over",
JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
running = false;
}
private Node createFood(){
int x = 0;
int y = 0;
do{
Random r = new Random();
x = r.nextInt(maxX);
y = r.nextInt(maxY);
}while(matrix[x][y]);
return new Node(x,y);
}
public void speedUp(){
timeInterval *= speedChangeRate;
}
public void speedDown(){
timeInterval /= speedChangeRate;
}
public void changePauseState(){
paused = !paused;
}
public String toString(){
String result = "";
for(int i=0; i<nodeArray.size(); ++i){
Node n = (Node)nodeArray.get(i);
result += "[" + n.x + "," + n.y + "]";
}
return result;
}
}
class Node{
int x;
int y;
Node(int x, int y){
this.x = x;
this.y = y;
}
}
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class TanChiShe implements KeyListener,ActionListener{
/**
* @param args
*/
int max = 300;//蛇長最大值
final int JianJu = 15; //設定蛇的運動網格間距(窗口最大32*28格)
byte fangXiang = 4; //控制蛇的運動方向,初始為右
int time = 500; //蛇的運動間隔時間
int jianTime = 2;//吃一個減少的時間
int x,y;//蛇的運動坐標,按網格來算
int x2,y2;//暫存蛇頭的坐標
int jiFenQi = 0;//積分器
boolean isRuned = false;//沒運行才可設級別
boolean out = false;//沒開始運行?
boolean run = false;//暫停運行
String JiBie = "中級";
JFrame f = new JFrame("貪吃蛇 V1.0");
JPanel show = new JPanel();
JLabel Message = new JLabel("級別:中級 蛇長:5 時間500ms 分數:00");
// JButton play = new JButton("開始");
JLabel sheTou;
JLabel shiWu;
JLabel sheWei[] = new JLabel[max];
static int diJi = 4; //第幾個下標的蛇尾要被加上
ImageIcon shang = new ImageIcon("tuPian\\isSheTouUp.png");//產生四個上下左右的蛇頭圖案
ImageIcon xia = new ImageIcon("tuPian\\isSheTouDown.png");
ImageIcon zhuo = new ImageIcon("tuPian\\isSheTouLeft.png");
ImageIcon you = new ImageIcon("tuPian\\isSheTouRight.png");
JMenuBar JMB = new JMenuBar();
JMenu file = new JMenu("開始游戲");
JMenuItem play = new JMenuItem(" 開始游戲 ");
JMenuItem pause = new JMenuItem(" 暫停游戲 ");
JMenu hard = new JMenu("游戲難度");
JMenuItem gao = new JMenuItem("高級");
JMenuItem zhong = new JMenuItem("中級");
JMenuItem di = new JMenuItem("低級");
JMenu about = new JMenu(" 關於 ");
JMenuItem GF = new JMenuItem("※高分榜");
JMenuItem ZZ = new JMenuItem("關於作者");
JMenuItem YX = new JMenuItem("關於游戲");
JMenuItem QK = new JMenuItem("清空記錄");
static TanChiShe tcs = new TanChiShe();
public static void main(String[] args) {
// TanChiShe tcs = new TanChiShe();
tcs.f();
}
public void f(){
f.setBounds(250,100,515,530);
f.setLayout(null);
f.setAlwaysOnTop(true);//窗口始終保持最前面
f.setBackground(new Color(0,0,0));
f.setDefaultCloseOperation(0);
f.setResizable(false);
f.setVisible(true);
// f.getContentPane().setBackground(Color.BLACK);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);//退出程序
}
});
f.setJMenuBar(JMB);
JMB.add(file);
file.add(play);
file.add(pause);
JMB.add(hard);
hard.add(gao);
hard.add(zhong);
hard.add(di);
JMB.add(about);
about.add(GF);
GF.setForeground(Color.blue);
about.add(ZZ);
about.add(YX);
about.add(QK);
QK.setForeground(Color.red);
f.add(show);
show.setBounds(0,f.getHeight()-92,f.getWidth(),35);
// show.setBackground(Color.green);
// f.add(play);
// play.setBounds(240,240,80,25);
play.addActionListener(this);
pause.addActionListener(this);
gao.addActionListener(this);
zhong.addActionListener(this);
di.addActionListener(this);
GF.addActionListener(this);
ZZ.addActionListener(this);
YX.addActionListener(this);
QK.addActionListener(this);
show.add(Message);
Message.setForeground(Color.blue);
f.addKeyListener(this);
// show.addKeyListener(this);
play.addKeyListener(this);
sheChuShi();
}
public void sheChuShi(){//蛇初始化
sheTou = new JLabel(you);//用向右的圖來初始蛇頭
f.add(sheTou);
sheTou.setBounds(JianJu*0,JianJu*0,JianJu,JianJu);
// System.out.println("ishere");
shiWu = new JLabel("■");
f.add(shiWu);
shiWu.setBounds(10*JianJu,10*JianJu,JianJu,JianJu);
for(int i=0;i<=diJi;i++) {
sheWei[i] = new JLabel("■");
f.add(sheWei[i]);
sheWei[i].setBounds(-1*JianJu,0*JianJu,JianJu,JianJu);
}
while(true){
if(out == true){
yunXing();
break;
}
try{
Thread.sleep(200);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
public void sheJiaChang(){//蛇的長度增加
if(diJi < max){
sheWei[++diJi] = new JLabel(new ImageIcon("tuPian\\isSheWei.jpg"));
f.add(sheWei[diJi]);
sheWei[diJi].setBounds(sheWei[diJi-1].getX(),sheWei[diJi-1].getY(),JianJu,JianJu);
// System.out.println("diJi "+diJi);
}
}
public void pengZhuanJianCe(){//檢測蛇的碰撞情況
if(sheTou.getX()<0 || sheTou.getY()<0 ||
sheTou.getX()>f.getWidth()-15 || sheTou.getY()>f.getHeight()-105 ){
gameOver();
// System.out.println("GameOVER");
}
if(sheTou.getX() == shiWu.getX() && sheTou.getY() == shiWu.getY()){
out: while(true){
shiWu.setLocation((int)(Math.random()*32)*JianJu,(int)(Math.random()*28)*JianJu);
for(int i=0;i<=diJi;i++){
if(shiWu.getX()!= sheWei[i].getX() && shiWu.getY()!=sheWei[i].getY()
&& sheTou.getX()!=shiWu.getX() && sheTou.getY()!= shiWu.getY()){//如果食物不在蛇身上則退出循環,產生食物成功
break out;
}
}
}
sheJiaChang();
// System.out.println("吃了一個");
if(time>100 ){
time -= jianTime;
}
else{}
Message.setText("級別:"+JiBie+" 蛇長:"+(diJi+2)+" 時間:"+time+"ms 分數:"+(jiFenQi+=10)+"");
}
for(int i=0;i<=diJi;i++){
if(sheTou.getX() == sheWei[i].getX() && sheTou.getY() == sheWei[i].getY()){
gameOver();
// System.out.println("吃到尾巴了");
}
}
}
public void yunXing(){
while(true){
while(run){
if(fangXiang == 1){//上
y-=1;
}
if(fangXiang == 2){//下
y+=1;
}
if(fangXiang == 3){//左
x-=1;
}
if(fangXiang == 4){//右
x+=1;
}
x2 = sheTou.getX();
y2 = sheTou.getY();
sheTou.setLocation(x*JianJu,y*JianJu); //設置蛇頭的坐標 網格數*間隔
for(int i=diJi;i>=0;i--){
if(i==0){
sheWei[i].setLocation(x2,y2);
// System.out.println(i+" "+sheTou.getX()+" "+sheTou.getY());
}
else{
sheWei[i].setLocation(sheWei[i-1].getX(),sheWei[i-1].getY());
// System.out.println(i+" "+sheWei[i].getX()+" "+sheWei[i].getY());
}
}
pengZhuanJianCe();
try{
Thread.sleep(time);
}catch(Exception e){
e.printStackTrace();
}
}
Message.setText("級別:"+JiBie+" 蛇長:"+(diJi+2)+" 時間:"+time+"ms 分數:"+(jiFenQi+=10)+"");
try{
Thread.sleep(200);
}catch(Exception e){
e.printStackTrace();
}
}
}
public void gameOver(){//游戲結束時處理
int in = JOptionPane.showConfirmDialog(f,"游戲已經結束!\n是否要保存分數","提示",JOptionPane.YES_NO_OPTION);
if(in == JOptionPane.YES_OPTION){
// System.out.println("YES");
String s = JOptionPane.showInputDialog(f,"輸入你的名字:");
try{
FileInputStream fis = new FileInputStream("GaoFen.ini");//先把以前的數據讀出來加到寫的數據前
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String s2,setOut = "";
while((s2=br.readLine())!= null){
setOut =setOut+s2+"\n";
}
FileOutputStream fos = new FileOutputStream("GaoFen.ini");//輸出到文件流
s = setOut+s+":"+jiFenQi+"\n";
fos.write(s.getBytes());
}catch(Exception e){}
}
System.exit(0);
}
public void keyTyped(KeyEvent arg0) {
// TODO 自動生成方法存根
}
public void keyPressed(KeyEvent arg0) {
// System.out.println(arg0.getSource());
if(arg0.getKeyCode() == KeyEvent.VK_UP){//按上下時方向的值相應改變
if(fangXiang != 2){
fangXiang = 1;
// sheTou.setIcon(shang);//設置蛇的方向
}
// System.out.println("UP");
}
if(arg0.getKeyCode() == KeyEvent.VK_DOWN){
if(fangXiang != 1){
fangXiang = 2;
// sheTou.setIcon(xia);
}
// System.out.println("DOWN");
}
if(arg0.getKeyCode() == KeyEvent.VK_LEFT){//按左右時方向的值相應改變
if(fangXiang != 4){
fangXiang = 3;
// sheTou.setIcon(zhuo);
}
// System.out.println("LEFT");
}
if(arg0.getKeyCode() == KeyEvent.VK_RIGHT){
if(fangXiang != 3){
fangXiang = 4;
// sheTou.setIcon(you);
}
// System.out.println("RIGHT");
}
}
public void keyReleased(KeyEvent arg0) {
// TODO 自動生成方法存根
}
public void actionPerformed(ActionEvent arg0) {
// TODO 自動生成方法存根
JMenuItem JI = (JMenuItem)arg0.getSource();
if(JI == play){
out = true;
run = true;
isRuned = true;
gao.setEnabled(false);
zhong.setEnabled(false);
di.setEnabled(false);
}
if(JI == pause){
run = false;
}
if(isRuned == false){//如果游戲還沒運行,才可以設置級別
if(JI == gao){
time = 200;
jianTime = 1;
JiBie = "高級";
Message.setText("級別:"+JiBie+" 蛇長:"+(diJi+2)+" 時間:"+time+"ms 分數:"+jiFenQi);
}
if(JI == zhong){
time = 400;
jianTime = 2;
JiBie = "中級";
Message.setText("級別:"+JiBie+" 蛇長:"+(diJi+2)+" 時間:"+time+"ms 分數:"+jiFenQi);
}
if(JI == di){
time = 500;
jianTime = 3;
JiBie = "低級";
Message.setText("級別:"+JiBie+" 蛇長:"+(diJi+2)+" 時間:"+time+"ms 分數:"+jiFenQi);
}
}
if(JI == GF){
try{
FileInputStream fis = new FileInputStream("GaoFen.ini");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String s,setOut = "";
while((s=br.readLine())!= null){
setOut =setOut+s+"\n";
}
if(setOut.equals("")){
JOptionPane.showMessageDialog(f,"暫無保存記錄!","高分榜",JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(f,setOut);
}
}catch(Exception e){
e.printStackTrace();
}
}
if(JI == ZZ){//關於作者
JOptionPane.showMessageDialog(f,"軟體作者:申志飛\n地址:四川省綿陽市\nQQ:898513806\nE-mail:[email protected]","關於作者",JOptionPane.INFORMATION_MESSAGE);
}
if(JI == YX){//關於游戲
JOptionPane.showMessageDialog(f,"貪吃蛇游戲\n游戲版本 V1.0","關於游戲",JOptionPane.INFORMATION_MESSAGE);
}
if(JI == QK){
try{
int select = JOptionPane.showConfirmDialog(f,"確實要清空記錄嗎?","清空記錄",JOptionPane.YES_OPTION);
if(select == JOptionPane.YES_OPTION){
String setOut = "";
FileOutputStream fos = new FileOutputStream("GaoFen.ini");//輸出到文件流
fos.write(setOut.getBytes());
}
}catch(Exception ex){}
}
}
}
//是我自己寫的,本來裡面有圖片的,但無法上傳,所以把圖片去掉了,裡面的ImageIcon等語句可以去掉。能正常運行。