贪吃蛇Controller Java实现(二)
package cn.tcc.snake.Controller;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import cn.tcc.snake.antition.Food;
import cn.tcc.snake.antition.Ground;
import cn.tcc.snake.antition.Sanke;
import cn.tcc.snake.listener.SnakeListener;
import cn.tcc.snake.tcc.View.GamePanel;
//处理用户按键事件有两种方法;
//1.实现一个接口;
//2.继承一个类 //只用到它的一个方法;
import cn.tcc.snake.util.Global;
public class Controller extends KeyAdapter implements SnakeListener{
@Override
public void SnakeMoved(Sanke snake) {
// TODO Auto-generated method stub
if(food.isSnakeEatFood(snake)){
snake.eatFood();
food.newFood(ground.getpoint());
}
if(ground.isSnakeEatRock(snake)){
snake.die();
}
if(snake.isEatBody()){
snake.die();
}
gamePanel.display(snake, food, ground);
}
private Sanke snake;
private Food food;
private Ground ground;
private GamePanel gamePanel;
public Controller(Sanke snake, Food food, Ground ground, GamePanel gamePanel) {
super();
this.snake = snake;
this.food = food;
this.ground = ground;
this.gamePanel = gamePanel;
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
snake.changDirection(snake.UP);
break;
case KeyEvent.VK_DOWN:
snake.changDirection(snake.DOWN);
break;
case KeyEvent.VK_LEFT:
snake.changDirection(snake.LEFT);
break;
case KeyEvent.VK_RIGHT:
snake.changDirection(snake.RIGHT);
break;
default:
break;
}
}
public void newGame(){
food.newFood(ground.getpoint());
snake.start();
}
}