;;;;;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tanchishe extends JFrame {
  private JPanel contentPane; //窗体内容网格
  private JButton btnStart = new JButton("开始"); //游戏开始按钮
  private JButton btnPause = new JButton("暂停"); //游戏暂停按钮
  private JButton btnExit = new JButton("退出"); //游戏退出按钮
  private JPanel pnlTop = new JPanel(); //顶部按钮和分数面板
  private JPanel pnlLeft = new JPanel(); //左侧面板
  private JPanel playPanel = new JPanel(); //游戏区面板
  private BorderLayout borderLayout1 = new BorderLayout(); //容器布局管理器
  private BorderLayout borderLayout2 = new BorderLayout();
  private GridLayout rbtnLayout = new GridLayout(10, 1, 1, 1);
  private static final int UP = 1,LEFT = 2,DOWN = 3,RIGHT = 4;//蛇运动方向
  private static final int ROWS = 30; //游戏区行数
  private static final int COLS = 50; //游戏区列数
  private boolean isPause = false; //游戏暂停标志
  private boolean isEnd; //游戏结束标志
  private SnakeBody snake; //贪食蛇
  private int score = 0; //当前得分
  SnakeThread thread = new SnakeThread(); //游戏主线程
  private GridLayout grid1 = new GridLayout(ROWS,COLS,0,0); //游戏区布局
  private JButton[][] blocks; //游戏区的所有方块
  JPanel jPanel2 = new JPanel();
  JLabel jLabel1 = new JLabel("得分:");
  JLabel lblScroe = new JLabel("0");
  ButtonGroup buttonGroup1 = new ButtonGroup();
  JRadioButton rbtnLow = new JRadioButton("初级", true);
  JRadioButton rbtnMid = new JRadioButton("中级");
  JRadioButton rbtnHigh = new JRadioButton("高级");
  public tanchishe() {
    super("贪食蛇游戏");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    contentPane = (JPanel)this.getContentPane();
    contentPane.setLayout(borderLayout2);
    this.setResizable(false);
    this.setSize(new Dimension(512, 414));
    keyAction keyAct = new keyAction();
    this.addKeyListener(keyAct);
    btnStart.addKeyListener(keyAct);
    btnPause.addKeyListener(keyAct);
    btnExit.addKeyListener(keyAct);
    rbtnLow.addKeyListener(keyAct);
    rbtnMid.addKeyListener(keyAct);
    rbtnHigh.addKeyListener(keyAct);
    btnAction btnAct = new btnAction();
    btnStart.addActionListener(btnAct);
    btnPause.addActionListener(btnAct);
    btnExit.addActionListener(btnAct);
    rbtnLow.addActionListener(btnAct);
    rbtnMid.addActionListener(btnAct);
    rbtnHigh.addActionListener(btnAct);
    pnlLeft.setLayout(borderLayout1);
    playPanel.setLayout(grid1);
    playPanel.setBackground(Color.white);
    playPanel.setBorder(BorderFactory.createEtchedBorder());
    jPanel2.setLayout(rbtnLayout);
    buttonGroup1.add(rbtnLow);
    buttonGroup1.add(rbtnMid);
    buttonGroup1.add(rbtnHigh);
    rbtnLow.setSelected(true);
    pnlLeft.add(playPanel);
    pnlLeft.add(jPanel2, BorderLayout.WEST);
    jPanel2.add("f1", rbtnLow);
    jPanel2.add("f2", rbtnMid);
    jPanel2.add("f3", rbtnHigh);
    pnlTop.add(btnStart);
    pnlTop.add(btnPause);
    pnlTop.add(btnExit);
    pnlTop.add(jLabel1);
    pnlTop.add(lblScroe);
    contentPane.add(pnlTop, BorderLayout.NORTH);
    contentPane.add(pnlLeft, BorderLayout.CENTER);
    //创建并初始化游戏区方块
    blocks = new JButton[ROWS][COLS];
    for (int i = 0; i < ROWS; i++) {
      for (int j = 0; j < COLS; j++) {
        blocks[i][j] = new JButton();
        blocks[i][j].setBackground(Color.lightGray);
        blocks[i][j].setVisible(false);
        playPanel.add(blocks[i][j]);
      }
    }
  }
  public static void main(String[] args) {
    tanchishe app = new tanchishe();
    app.validate();
    app.setVisible(true);
  }
  public void start() {
    snake = new SnakeBody(); //创建蛇身
    if (rbtnLow.isSelected())
      snake.setSpeed(300);
    if (rbtnMid.isSelected())
      snake.setSpeed(300);
    if (rbtnHigh.isSelected())
      snake.setSpeed(100);
    score = 0;
    isPause = false;
    isEnd = false; //
    btnPause.setText("暂停");
    //初始化游戏区
    for (int i = 0; i < ROWS; i++) {
      for (int j = 0; j < COLS; j++) {
        blocks[i][j].setBackground(Color.lightGray);
        blocks[i][j].setVisible(false);
      }
    }
    //在游戏区内随机放置豆
    int x = (int) (Math.random() * ROWS);
    int y = (int) (Math.random() * COLS);
    while (blocks[x][y].isVisible()) {
      x = (int) (Math.random() * ROWS);
      y = (int) (Math.random() * COLS);
    }
    blocks[x][y].setBackground(Color.yellow);
    blocks[x][y].setVisible(true);
    try {
      thread.start();
    }
    catch (IllegalThreadStateException illegalThreadStateException) {}
  }
  class SnakeBody {
    public int row[];
    public int col[];
    public int len = 3, direction = RIGHT, lastdirection = RIGHT;
    public long speed = 300;
    public SnakeBody() {
      len = 3;
      direction = RIGHT;
      lastdirection = RIGHT;
      row = new int[ROWS];
      col = new int[COLS];
      for (int i = 0; i <= len; i++) {
        row[i] = 1;
        col[i] = len - i;
      }
    }
    public void setSpeed(int s) {
      speed = s;
    }
    public void move() {
      blocks[row[len]][col[len]].setVisible(false); //去掉蛇尾
      blocks[row[len]][col[len]].setBackground(Color.white); //修改颜色
      //显示蛇身
      for (int i = 0; i < len; i++) {
        blocks[row[i]][col[i]].setBackground(Color.green);
        blocks[row[i]][col[i]].setVisible(true);
      }
      //移动蛇身
      for (int i = len; i > 0; i--) {
        row[i] = row[i - 1];
        col[i] = col[i - 1];
      }
      //根据蛇身运动方向,决定蛇头位置
      switch (direction) {
        case UP: {
          if (lastdirection == DOWN)
            row[0] += 1;
          else {
            row[0] -= 1;
            lastdirection = UP;
          }
          break;
        }
        case LEFT: {
          if (lastdirection == RIGHT)
            col[0] += 1;
          else {
            col[0] -= 1;
            lastdirection = LEFT;
          }
          break;
        }
        case DOWN: {
          if (lastdirection == UP)
            row[0] -= 1;
          else {
            row[0] += 1;
            lastdirection = DOWN;
          }
          break;
        }
        case RIGHT: {
          if (lastdirection == LEFT)
            col[0] -= 1;
          else {
            col[0] += 1;
            lastdirection = RIGHT;
          }
          break;
        }
      }
      //当蛇头碰到墙时,蛇头碰到蛇身时,游戏结束
      if (row[0] >= ROWS || row[0] < 0 || col[0] >= COLS || col[0] < 0 ||
          blocks[row[0]][col[0]].getBackground().equals(Color.green)) {
        isEnd = true;
        JOptionPane.showMessageDialog(null, "游戏结束!");
      }
      //吃豆
      if (blocks[row[0]][col[0]].getBackground().equals(Color.yellow)) {
        score += 100;
        lblScroe.setText(Integer.toString(score));
        if (score % 2000 == 0 && speed > 100) {
          JOptionPane.showMessageDialog(null, "恭喜你过关了,准备进入下一关");
          speed -= 100;
          if (speed == 200)
            rbtnMid.setSelected(true);
          if (speed == 100)
            rbtnHigh.setSelected(true);
        }
      }
      //吃豆后,蛇身加长,并随机显示下一个豆
      if (blocks[row[0]][col[0]].getBackground().equals(Color.yellow)) {
        len++;
        int x, y;
        x = (int) (Math.random() * ROWS);
        y = (int) (Math.random() * COLS);
        while (blocks[x][y].isVisible()) {
          x = (int) (Math.random() * ROWS);
          y = (int) (Math.random() * COLS);
        }
        blocks[x][y].setBackground(Color.yellow);
        blocks[x][y].setVisible(true);
      }
      blocks[row[0]][col[0]].setBackground(Color.green);
      blocks[row[0]][col[0]].setVisible(true); //显示蛇头
    }
  }
  class SnakeThread extends Thread {
    public void run() {
      while (true) {
        try {
          Thread.sleep(snake.speed); //控制移动速度
          if (!isEnd && !isPause) {
            snake.move(); //移动蛇身
          }
          if (isEnd) { //游戏结束
            btnStart.setEnabled(true);
          }
        }
        catch (Exception ex) {}
      }
    }
  }
  class keyAction extends KeyAdapter {
    public void keyPressed(KeyEvent e) {
      if (!isEnd && !isPause) {
        //根据用户按键,设置蛇运动方向
        if (e.getKeyCode() == KeyEvent.VK_UP) {
          snake.direction = UP;
        }
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {
          snake.direction = DOWN;
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
          snake.direction = LEFT;
        }
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
          snake.direction = RIGHT;
        }
      }
    }
  }
  //按钮监听响应处理类
  private class btnAction implements ActionListener {
    public void actionPerformed(ActionEvent ae) {
      Object source = ae.getSource();
      if (source.equals(btnStart)) {
        btnStart.setEnabled(false);
        start();
      }
      if (source.equals(btnPause)) {
        if (isPause == true) {
          btnPause.setText("暂停");
        }
        if (isPause == false) {
          btnPause.setText("继续");
        }
        isPause = !isPause;
      }
      if (source.equals(btnExit)) {
        System.exit(0);
      }
      if (source.equals(rbtnLow)) {
        snake.setSpeed(300);
      }
      if (source.equals(rbtnMid)) {
        snake.setSpeed(200);
      }
      if (source.equals(rbtnHigh)) {
        snake.setSpeed(100);
      }
    }
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值