package worm;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JPanel;
public class WormStage extends JPanel{
private Food food ;
private Worm worm ;
private Timer timer =new Timer() ;
public WormStage(){
worm = new Worm() ;
food = randomFood() ;
}
//重写父类中的paint方法
public void paint(Graphics g){
super.paint(g) ;
//画食物
g.setColor(food.getColor()) ;
g.fillRect(food.getX(), food.getY(), food.getWidth(), food.getHeight());
//画蛇
for(int i = 0 ; i<worm.getCells().length; i++){
Cell cell = worm.getCells()[i] ;
g.setColor(cell.getColor()) ;
//g.fillRect(cell.getX(), cell.getY(), cell.getWidth(), cell.getHeight()) ;
g.fill3DRect(cell.getX(), cell.getY(), cell.getWidth(), cell.getHeight(), true) ;
}
}
//内部类
class MyKey extends KeyAdapter{
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode() ;
if(c == KeyEvent.VK_UP){
if(worm.headBreak(Worm.UP, Util.STAGE_ROWS, Util.STAGE_COLS)){
System.out.println("撞到上边的墙,或者吃掉自己") ;
//重新开始的处理
restart() ;
return ;
}
if(worm.stepForEat(Worm.UP, food)) {
//吃掉食物
food = randomFood() ;
}
}
if(c == KeyEvent.VK_DOWN){
if(worm.headBreak(Worm.DOWN, Util.STAGE_ROWS, Util.STAGE_COLS)){
System.out.println("撞到下边的墙或者是吃掉自己") ;
restart() ;
return ;
}
if(worm.stepForEat(Worm.DOWN, food)) {
food = randomFood();
}
}
if(c == KeyEvent.VK_LEFT){
if(worm.headBreak(Worm.LEFT, Util.STAGE_ROWS, Util.STAGE_COLS)){
System.out.println("撞到左边的墙或者是吃掉自己");
restart() ;
return ;
}
if(worm.stepForEat(Worm.LEFT, food)) {
food = randomFood() ;
}
}
if(c == KeyEvent.VK_RIGHT){
if(worm.headBreak(Worm.RIGHT, Util.STAGE_ROWS, Util.STAGE_COLS)){
System.out.println("撞到右边的墙或者是吃掉自己");
restart() ;
return ;
}
if(worm.stepForEat(Worm.RIGHT, food)) {
food = randomFood() ;
}
}
//paint 系统调用的
repaint() ;//通知系统去调用paint方法
}
}
//定义任务
// class Runner extends TimerTask{
// public void run(){
// //1.判断走一步是否撞墙
// if(worm.headBreak(Util.STAGE_ROWS, Util.STAGE_COLS)){
// restart() ;
// return ;
// }
// //2.走一步
// if(worm.stepForEat(food)){
// food = randomFood() ;
// }
// repaint() ;
// }
// }
//定义启动游戏的方法
public void go(){
//添加定时器任务
//timer.schedule(new Runner(), 0,100) ;
//匿名内部类
timer.schedule(new TimerTask(){
public void run(){
//1.判断走一步是否撞墙
if(worm.headBreak(Util.STAGE_ROWS, Util.STAGE_COLS)){
restart() ;
return ;
}
//2.走一步
if(worm.stepForEat(food)){
food = randomFood() ;
}
repaint() ;
}
}, 0,700) ;
//获取键盘的焦点
this.requestFocus() ;
this.addKeyListener(new MyKey()) ;
}
//追加随机生成食物的方法
public Food randomFood(){
Random random = new Random() ;
// while(true){
//
// }
int i ;
int j ;
for(;;){
i = random.nextInt(Util.STAGE_ROWS);
j = random.nextInt(Util.STAGE_COLS);
if(worm.contains(i, j)){
continue ;
}
return new Food(i,j) ;
}
}
//追加重新开始的方法
public void restart(){
worm = new Worm();
food = randomFood() ;
//绘制
repaint() ;
}
}