日期:2014-05-20 浏览次数:20812 次
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(); } } }
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); } }