?? snake.java
字號:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Snake 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 Snake() {
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) {
Snake app = new Snake();
app.validate();
app.setVisible(true);
}
public void start() {
snake = new SnakeBody(); //創建蛇身
if (rbtnLow.isSelected())
snake.setSpeed(300);
if (rbtnMid.isSelected())
snake.setSpeed(200);
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);
}
}
}
}
?? 快捷鍵說明
復制代碼
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -