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

求助,贪食蛇问题
Java code

package 贪食蛇;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**随机产生Apple(贪食蛇食物)*/
public class Apple extends JPanel{
    private int x;    //Apple 随机位置的x坐标
    private int y;    //Apple 随机位置的y坐标
    
    public Apple(){
        int tempX=(int)(Math.random()*22);
        int tempY=(int)(Math.random()*22);
        setX(tempX);
        setY(tempY);
        //创建一个Timer
        Timer timer=new Timer(1000,new TimerListener());
        timer.start();
    }
    
    //设定Apple横坐标
    public void setX(int x){
        this.x=x;
    }
    
    //设定Apple纵坐标
    public void setY(int y){
        this.y=y;
    }
    
    //获取Apple的横坐标
    public int getX(){
        return this.x;
    }
    
    //获取Apple的纵坐标
    public int getY(){
        return this.y;
    }
    
    //画出Apple
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawRect(0, 0, 220, 220);
        
        g.fillRect(getX()*10, getY()*10, 10, 10);
        System.out.println("x:"+getX()+"\t"+"y:"+getY());
        
        
        int tempX=(int)(Math.random()*22);
        int tempY=(int)(Math.random()*22);
        setX(tempX);
        setY(tempY);
    }
    
    class TimerListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            repaint();
        }
    }
    
}


Java code

package 贪食蛇;
import javax.swing.*;;

public class Snakes1 extends JFrame{
    public Snakes1(){
        //创建一个Apple对象
        add(new Apple());
    }

    public static void main(String[] args) {
        // TODO 自动生成方法存根
        Snakes1 frame=new Snakes1();
        frame.setTitle("Snakes1");
        frame.setSize(250,250);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

}


这是我写贪食蛇的第一步
写的很不顺,我写了个Apple()类贪食蛇的食物,为此我写了个测试,让它每秒钟在画板上随机画一次,
我采用的方法是,就像每次那张纸画个画,然后把原来的盖上
可运行的结果就是每次盖不齐,不知道怎么解决,或者有更好的思路

------解决方案--------------------
建议你需要有多层概念,也就是场景背景与物体背景(蛇苹果)应该是两个不同的图层,更新区域需要做图层覆盖或叠加。
------解决方案--------------------
你的Apple类应该设置Width、Height,在paintComponent的时候只需重画Width、Height覆盖的区域。

不过我不是太理解你说的“盖不齐”,能不能截张图来看看?