⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mainframe.java

📁 希望大家多多交流
💻 JAVA
字号:
package system;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import snake.*;
import food.*;

public class MainFrame
    extends JFrame
    implements KeyListener {
  private MainPanel mPanel; //贪吃蛇移动所在的面板
  private AttPanel attPanel; //属性面板,显示等级得分等信息
  private Snake snake; //贪吃蛇
  private Food food; //食物

  private int score = 0; //得分
  private int level = Speed.LEVER_ONE; //难度等级

  //是否是新开始的游戏,用来控制GO字符串的绘制
  private boolean isNewGame = false;
  //贪吃蛇是否死亡
  private boolean isGameOver = false;
  //显示开头画面
  private boolean isWelcome = true;
  //显示Level Up字符
  private boolean isLevelUp = false;

  //菜单
  private JMenuItem start; //开始新游戏
  private JMenuItem stop; //暂停游戏
  private JMenuItem goOn; //继续游戏

  private static final int WIDTH = 700;
  private static final int HEIGHT = 554;

  public MainFrame() {
    Config.loadSystemConfig(); //读取系统配置

    this.addKeyListener(this); //注册键盘监听器
    this.initMenu();

    this.mPanel = new MainPanel(this);
    this.snake = new Snake(this, Direction.UP); //初始化贪吃蛇
    this.snake.setLocation(460, 440); //设置蛇的初始位置
    this.food = new Food(this);
    this.attPanel = new AttPanel(this); //初始化属性面板

    Container con = this.getContentPane();
    //将窗体分割为左右两块,左面为蛇移动的面板,右面为属性面板
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                          this.mPanel, this.attPanel);
    splitPane.setDividerLocation(501); //设置分割窗体的位置
    splitPane.setDividerSize(2); //设置分割条的宽度,为0表示以固定方式分割窗体
    con.add(splitPane);
  }

  //初始化菜单
  public void initMenu() {
    JMenuBar b = new JMenuBar();

    //========================创建系统菜单及下属菜单项==========================
    JMenu sys = new JMenu("系统(S)");
    sys.setMnemonic('S');

    start = new JMenuItem("开始新游戏");
    String key = KeyEvent.getKeyText(Config.START);
    start.setAccelerator(KeyStroke.getKeyStroke(key)); //设置快捷键

    goOn = new JMenuItem("继续");
    goOn.setAccelerator(KeyStroke.getKeyStroke(Config.CONTINUE,0)); //设置快捷键

    stop = new JMenuItem("暂停");
    stop.setAccelerator(KeyStroke.getKeyStroke(Config.STOP,0)); //设置快捷键

    //注册开始新游戏菜单的监听器
    start.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        startNewGame();
      }
    });

    //注册继续游戏菜单的监听器
    goOn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        continueGame();
      }
    });

    //注册暂停游戏菜单的监听器
    stop.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        stopGame();
      }
    });

    JMenuItem hero = new JMenuItem("排行榜");
    hero.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        Hero.showHeroDialog(MainFrame.this);
      }
    });

    JMenuItem setting = new JMenuItem("设置");
    setting.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        KeySet.showKeySetDialog(MainFrame.this); //显示按键设置界面
      }
    });

    JMenu bgSelect = new JMenu("选择背景");
    JRadioButtonMenuItem grass = new JRadioButtonMenuItem("草地");
    grass.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Config.CURRENT_BG = Config.BG_GRASS; //更改背景
        Config.saveSystemConfig();
        mPanel.repaint(); //绘制更改后的背景
      }
    });
    JRadioButtonMenuItem square = new JRadioButtonMenuItem("水晶方格");
    square.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Config.CURRENT_BG = Config.BG_SQUARE; //更改背景
        Config.saveSystemConfig();
        mPanel.repaint(); //绘制更改后的背景
      }
    });
    JRadioButtonMenuItem wall = new JRadioButtonMenuItem("围墙");
    wall.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Config.CURRENT_BG = Config.BG_WALL; //更改背景
        Config.saveSystemConfig();
        mPanel.repaint(); //绘制更改后的背景
      }
    });
    JRadioButtonMenuItem wood = new JRadioButtonMenuItem("木地板");
    wood.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Config.CURRENT_BG = Config.BG_WOOD; //更改背景
        Config.saveSystemConfig();
        mPanel.repaint(); //绘制更改后的背景
      }
    });

    //把单选按钮菜单添加到一组
    ButtonGroup group = new ButtonGroup();
    group.add(grass);
    group.add(square);
    group.add(wall);
    group.add(wood);

    bgSelect.add(grass);
    bgSelect.add(square);
    bgSelect.add(wall);
    bgSelect.add(wood);

    JMenuItem exit = new JMenuItem("结束游戏");
    exit.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.exit(0); //退出游戏
      }
    });

    sys.add(start); //开始新游戏菜单项
    sys.add(stop); //停止
    sys.add(goOn); //继续
    sys.addSeparator();
    sys.add(hero);
    sys.add(setting);
    sys.add(bgSelect);
    sys.addSeparator();
    sys.add(exit); //退出

    //========================创建帮助菜单及下属菜单项==========================
    JMenu help = new JMenu("帮助(H)");
    help.setMnemonic('H');

    JMenuItem aboutSnake = new JMenuItem("关于贪吃蛇");
    aboutSnake.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        About.showAboutDialog(MainFrame.this,"as.inf");
      }
    });

    JMenuItem aboutUs = new JMenuItem("关于我们");
    aboutUs.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        About.showAboutDialog(MainFrame.this,"au.inf");
      }
    });

    help.add(aboutSnake);
    help.add(aboutUs);

    //=======================把菜单添加到菜单条================================
    b.add(sys);
    b.add(help);
    this.setJMenuBar(b);

    //设置菜单和按钮的初始状态
    stop.setEnabled(false);
    goOn.setEnabled(false);

    //===================把默认的背景所对应的背景选项设置为选中===================
    if (Config.CURRENT_BG.equalsIgnoreCase(Config.BG_GRASS)) {
      grass.setSelected(true);
    }
    else if (Config.CURRENT_BG.equalsIgnoreCase(Config.BG_SQUARE)) {
      square.setSelected(true);
    }
    else if (Config.CURRENT_BG.equalsIgnoreCase(Config.BG_WOOD)) {
      wood.setSelected(true);
    }
    else if (Config.CURRENT_BG.equalsIgnoreCase(Config.BG_WALL)) {
      wall.setSelected(true);
    }
  }

  //开始新游戏
  public void startNewGame() {
    stop.setEnabled(true);
    this.attPanel.getStopButton().setEnabled(true);
    goOn.setEnabled(false);
    this.attPanel.getGoOnButton().setEnabled(false);

    snake.setSpeed(Speed.SPEED_ONE);
    snake.setLocation(460, 440);
    snake.changeDirection(Direction.UP);
    snake.setPreDirection(Direction.UP); //因为蛇初始化时是垂直方向的
    snake.resize(); //重新初始化蛇身大小

    food.changeLocation(); //更新食物
    isNewGame = true; //开始新游戏,用于绘制GO字符
    isWelcome = false; //不显示开头画面
    isGameOver = false; //不显示Game Over字符

    snake.startToMove(); //贪吃蛇开始移动
    System.out.println("MainFrame.java-----贪吃蛇开始移动!");

    //==================开启一个新线程控制GO的显示========================
    new Thread() {
      public void run() {
        try {
          Thread.sleep(2000); //显示“GO!!!”字符串两秒
        }
        catch (InterruptedException e) {
          e.printStackTrace();
        }

        isNewGame = false;
      }
    }

    .start();
  }

  //暂停游戏
  public void stopGame() {
    stop.setEnabled(false);
    this.attPanel.getStopButton().setEnabled(false);
    goOn.setEnabled(true);
    this.attPanel.getGoOnButton().setEnabled(true);

    snake.stop(); //贪吃蛇停止移动
    System.out.println("MainFrame.java----停止移动!");
  }

  //继续游戏
  public void continueGame() {
    goOn.setEnabled(false);
    this.attPanel.getGoOnButton().setEnabled(false);
    stop.setEnabled(true);
    this.attPanel.getStopButton().setEnabled(true);

    snake.moveOn(); //贪吃蛇继续移动
    System.out.println("MainFrame.java-----贪吃蛇开始移动!");

  }

  //返回贪吃蛇移动的主面板
  public MainPanel getMainPanel() {
    return this.mPanel;
  }

  //返回贪吃蛇
  public Snake getSnake() {
    return this.snake;
  }

  //返回食物
  public Food getFood() {
    return this.food;
  }

  //返回难度等级
  public int getLevel() {
    return this.level;
  }

  //设置难度等级
  public void setLevel(int l) {
    this.level = l;
  }

  //难度等级提升一级
  public void levelUp() {
    if (this.level < Speed.MAX_LEVEL) {
      this.level++;
      this.isLevelUp = true;//显示Level Up提示字符
      this.snake.speedUp(); //提升蛇的移动速度
      this.attPanel.setLevel(this.level);

      //=====================开启一个新线程来控制Level Up的显示===================
      new Thread() {
        public void run(){
          try{
            Thread.sleep(1000);//显示Level Up一秒
          }
          catch(InterruptedException e){
            e.printStackTrace();
          }

          isLevelUp = false;
        }
      }

      .start();
    }
  }

  //判断贪吃蛇是否应该提升一级
  public boolean shouldLevelUp() {
    if (this.level == Speed.MAX_LEVEL || this.level == Speed.LEVER_FIVE) {
      return false; //已达到最高等级
    }
    else if (this.level == Speed.LEVER_FOUR && this.score >= 20) {
      return true;
    }
    else if (this.level == Speed.LEVER_THREE && this.score >= 15) {
      return true;
    }
    else if (this.level == Speed.LEVER_TWO && this.score >= 10) {
      return true;
    }
    else if (this.level == Speed.LEVER_ONE && this.score >= 5) {
      return true;
    }
    return false;
  }

  //增加得分
  public void addScore(int s) {
    this.score += s;
    this.attPanel.setScore(this.score);//显示得分
  }

  //设置得分
  public void setScore(int s) {
    this.score = s;
  }

  public int getScore(){
    return this.score;
  }

  //是否是新开始的游戏
  public boolean isNewGame() {
    return this.isNewGame;
  }

  public void setNewGame(boolean b) {
    this.isNewGame = b;
  }

  //是否Game Over
  public boolean isGameOver() {
    return this.isGameOver;
  }

  public void setGameOver(boolean b) {
    this.isGameOver = b;
  }

  //是否显示开头画面
  public boolean isWelcome() {
    return this.isWelcome;
  }

  public void setWelcome(boolean b) {
    this.isWelcome = b;
  }

  //是否升了一级
  public boolean isLevelUp(){
    return this.isLevelUp;
  }

  public void setLevelUp(boolean b){
    this.isLevelUp = b;
  }

  //冲击排行榜
  public void addToHeroInfos(){
    String name = JOptionPane.showInputDialog(this,"请输入您的大名:",
                                "输入",JOptionPane.INFORMATION_MESSAGE);
    if(name == null || name.trim().length() < 1){
      return;
    }
    //更新排行榜信息
    Hero.updateHeroInfos(name,this.getScore());
  }

  //==================实现KeyListener接口==================================
  public void keyPressed(KeyEvent e) { //键按下
    int keyCode = e.getKeyCode();
    //改变贪吃蛇的运动方向
    if (keyCode == Config.UP) {
      this.snake.changeDirection(Direction.UP); //向上
    }
    else if (keyCode == Config.DOWN) {
      this.snake.changeDirection(Direction.DOWN); //向下
    }
    else if (keyCode == Config.LEFT) {
      this.snake.changeDirection(Direction.LEFT); //向左
    }
    else if (keyCode == Config.RIGHT) {
      this.snake.changeDirection(Direction.RIGHT); //向右
    }
  }

  public void keyTyped(KeyEvent e) { //键输入

  }

  public void keyReleased(KeyEvent e) { //键弹起

  }

  //=====================================================================

  public void show() {
    this.setTitle(Config.GAME_NAME);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setResizable(false);
    this.setSize(MainFrame.WIDTH, MainFrame.HEIGHT);

    Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
    int width = size.width;
    int height = size.height;
    this.setLocation( (width - MainFrame.WIDTH) / 2,
                     (height - MainFrame.HEIGHT) / 2);

    super.show();
  }
} //:~zj

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -