Snake.java
上传用户:benlin99
上传日期:2022-05-02
资源大小:8k
文件大小:3k
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import java.util.*;
- public class Snake implements KeyListener{
- JFrame main;
- Canvas paintCanvas;
- JLabel label;
- SnakeModel snakeModel=null;
- public Snake() {
- main = new JFrame("贪吃蛇");
- Container cp = main.getContentPane();
- label = new JLabel("得分:");
- cp.add(label, BorderLayout.NORTH);
- paintCanvas = new Canvas();
- paintCanvas.setSize(300,300);
- paintCanvas.addKeyListener(this);
- cp.add(paintCanvas, BorderLayout.CENTER);
- JPanel panelButtom = new JPanel();
- panelButtom.setLayout(new BorderLayout());
- JLabel labelHelp;
- labelHelp = new JLabel("向上,向下键可以加速;", JLabel.CENTER);
- panelButtom.add(labelHelp, BorderLayout.NORTH);
- labelHelp = new JLabel("回车键开始;", JLabel.CENTER);
- panelButtom.add(labelHelp, BorderLayout.CENTER);
- labelHelp = new JLabel("空格键暂停;",JLabel.CENTER);
- panelButtom.add(labelHelp, BorderLayout.SOUTH);
- cp.add(panelButtom,BorderLayout.SOUTH);
- main.addKeyListener(this);
- main.pack();
- main.setBounds(200, 200, 305, 405);
- main.setResizable(false);
- main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- main.setVisible(true);
- begin();
- }
- public void keyPressed(KeyEvent e){
- int keyCode = e.getKeyCode();
- if (snakeModel.running)
- switch(keyCode){
- case KeyEvent.VK_UP:
- snakeModel.changeDirection(SnakeModel.UP);
- break;
- case KeyEvent.VK_DOWN:
- snakeModel.changeDirection(SnakeModel.DOWN);
- break;
- case KeyEvent.VK_LEFT:
- snakeModel.changeDirection(SnakeModel.LEFT);
- break;
- case KeyEvent.VK_RIGHT:
- snakeModel.changeDirection(SnakeModel.RIGHT);
- break;
- case KeyEvent.VK_PAGE_UP:
- snakeModel.speedUp();
- break;
- case KeyEvent.VK_PAGE_DOWN:
- snakeModel.speedDown();
- break;
- case KeyEvent.VK_SPACE:
- snakeModel.changePauseState();
- break;
- default:
- }
- if (keyCode == KeyEvent.VK_ENTER){
- snakeModel.running = false;
- begin();
- }
- }
- public void keyReleased(KeyEvent e){}
- public void keyTyped(KeyEvent e){}
- void repaint(){
- Graphics g = paintCanvas.getGraphics();
- //绘制背景
- g.setColor(Color.GRAY);
- g.fillRect(0,0,300,300);
- // 绘制贪吃蛇
- g.setColor(Color.ORANGE);
- LinkedList na = snakeModel.nodeArray;
- Iterator it = na.iterator();
- while(it.hasNext()){
- Node n = (Node)it.next();
- drawNode(g,n);
- }
- // 绘制食物
- g.setColor(Color.PINK);
- Node n = snakeModel.food;
- drawNode(g,n);
- updateScore();
- }
- private void drawNode(Graphics g, Node n){
- g.fillRect(n.x*10,n.y*10,9,9);
- }
- public void updateScore(){
- String s = "得分:" + snakeModel.score;
- label.setText(s);
- }
- void begin(){
- if (snakeModel == null || !snakeModel.running){
- snakeModel = new SnakeModel(this,30,30);
- (new Thread(snakeModel)).start();
- }
- }
- public static void main(String[] args){
- new Snake();
- }
- }