日期:2014-05-20  浏览次数:20741 次

贪吃蛇
运行之后蛇块无法与食物块重叠导致无法吃食物……为什么??

package greedsnake;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;

public class SnakeWindow extends JFrame {
  public SnakeWindow(){
  setTitle("贪吃蛇");
  setLocation(200, 200);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setSize(450, 440);
  this.setVisible(true);
 
  mainPanel main=new mainPanel();
  this.getContentPane().add(BorderLayout.CENTER,main);
 
  }
   
  public static void main(String[] args){
  new SnakeWindow();
 
  }
}

package greedsnake;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class mainPanel extends JPanel{
JButton start,stop;
  int fenshu=0;
boolean starto=false;
Random r=new Random();
int sx=0,sy=0;
int temp=1;
JDialog dialog=new JDialog();
JLabel label=new JLabel("game over!");
JButton button=new JButton("OK");
Thread thread;
ArrayList<SnakeAct> list=new ArrayList<SnakeAct>();
public mainPanel() {
this.setLayout(new FlowLayout(FlowLayout.LEFT));

dialog.setLayout(new GridLayout(2,1));
dialog.add(label);
dialog.add(button);
dialog.setVisible(false);

button.addActionListener(new buttonListener());

start=new JButton("开始");
this.add(start);
start.addActionListener(new StartActionListener());
   
stop=new JButton("退出");
this.add(stop);
stop.addActionListener(new StopActionListener());
 
this.addKeyListener(new MyKeyListener());
}


public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawRect(10, 40, 400, 350);
g.drawString("分数:"+fenshu, 200, 25);
if(starto){
g.setColor(Color.BLUE);
g.fillRect(10+sx, 40+sy, 10, 10);
for(int i=0;i<list.size();i++){
g.setColor(Color.RED);
g.fillRect(10+list.get(i).getX()*10, 40+list.get(i).getY()*10, 10, 10);
}
}
}

public void move(int x,int y){
otherMove();
if(minOk(x, y)&&maxOk(x, y)){
list.get(0).setY(list.get(0).getY()+y);
list.get(0).setX(list.get(0).getX()+x);
eat();
repaint();
}else{ //死亡方法
dialog.setVisible(true);
dialog.setSize(200, 100);
dialog.setLocation(200, 200);
thread=null;
}
}

public void eat(){
if((sx==list.get(0).getX())&&(sy==list.get(0).getY())){

fenshu+=10;
sx=r.nextInt(390);
sy=r.nextInt(340);
SnakeAct temp=new SnakeAct();
temp.setX(list.get(list.size()-1).getX());
temp.setY(list.get(list.size()-1).getY());
list.add(temp);
}
}

public void otherMove(){
SnakeAct temp=new SnakeAct();
for(int i=0;i<list.size();i++){
if(i==1){
list.get(i).setX(list.get(0).getX());
list.get(i).setY(list.get(0).getY());
}else if(i>1){
temp=list.get(i-1);
list.set(i-1, list.get(i));
list.set(i, temp);

}
}
}

public boolean minOk(int x,int y){
if((list.get(0).getX()+x<0)||(list.get(0).getY()+y<0)){

return false;
}
for(int i=0;i<list.size();i++){
if(i>0&&list.get(0).getX()==list.get(i).getX()&&list.get(0).getY()==list.get(i).getY()){
return false;
}
}
return true;