62,614
社区成员
发帖
与我相关
我的任务
分享
public class Game {
public static void main(String[] args) {
Snake snake = new Snake();
Food food = new Food();
Ground ground = new Ground();
GamePanel gamePanel = new GamePanel();
Controller controller = new Controller(snake, food, ground, gamePanel);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(gamePanel, BorderLayout.CENTER);
gamePanel.addKeyListener(controller);
snake.addSnakeListener(controller);//如果把这个类屏蔽掉,就会报空指针
frame.setVisible(true);
controller.startGame();
}
}
public class GamePanel extends JPanel {
private Snake snake;
private Food food;
private Ground ground;
public void display(Snake snake, Food food, Ground ground) {
System.out.println("GamePanel display is done");
System.out.println("snake ==== " + snake);
this.food = food;
this.snake = snake;
this.ground = ground;
this.repaint();
}
@Override
protected void paintComponent(Graphics g) {
// 重新显示
this.snake.showMe();//这边会报snake为空指针
this.food.showMe();
this.ground.showMe();
}
}
public class Snake {
private Set<SnakeListener> snakeListener = new HashSet<SnakeListener>();
public void addSnakeListener(SnakeListener l) {
if (l != null) {
this.snakeListener.add(l);
}
}
public void move() {
System.out.println("snake move is done");
}
public void eatFood() {
System.out.println("snake eatFood is done");
}
public void changeDirection() {
System.out.println("snake changeDirection is done");
}
public boolean isEatBody() {
System.out.println("snake isEatBody is done");
return false;
}
public void showMe() {
System.out.println("snake showMe is done");
}
private class SnakeDriver implements Runnable {
@Override
public void run() {
// 蛇是否活着
boolean isSnakeLive = true;
while (isSnakeLive) {
move();
for (SnakeListener l : snakeListener) {
l.snakeMoved(Snake.this);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void start() {
new Thread(new SnakeDriver()).start();
}
}