標籤:貪吃蛇 小程式 java 遊戲
<p>class Control代碼:</p><p>import java.awt.event.KeyEvent;</p>import java.awt.event.KeyListener;public class Control implements KeyListener { //對鍵盤進行監聽SnakeModel snake=null;public Control(SnakeModel snake) {this.snake=snake;}@Overridepublic void keyPressed(KeyEvent e) {if(e.getKeyCode()==KeyEvent.VK_UP){snake.changeDirection(SnakeModel.UP);}if(e.getKeyCode()==KeyEvent.VK_DOWN){ //監聽按鍵↓,向下移動snake.changeDirection(SnakeModel.DOWN);}if(e.getKeyCode()==KeyEvent.VK_LEFT){ //監聽按鍵←,向左移動snake.changeDirection(SnakeModel.LEFT);}if(e.getKeyCode()==KeyEvent.VK_RIGHT){ //監聽按鍵↑,向上移動snake.changeDirection(SnakeModel.RIGHT);}if(e.getKeyCode()==KeyEvent.VK_RIGHT){ //監聽按鍵→,向右移動snake.changeDirection(SnakeModel.RIGHT);}if(e.getKeyCode()==KeyEvent.VK_R){//監聽按鍵R,重設snake.reStart();}}@Overridepublic void keyTyped(KeyEvent e) {}@Overridepublic void keyReleased(KeyEvent e) {}}
class SnakeModel 代碼:
<pre name="code" class="java">import java.awt.Canvas;import java.awt.Color;import java.awt.Graphics;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Random;import javax.swing.Timer;import cn.hncu.xh.Snake.snakePoint.point;/* * 思路: 利用動態數組裝蛇模型,蛇身的點都只跟著蛇頭(即:數組的第一個元素)動, * 每 repaint()一次,就把動態數組裡面的蛇全部數出來。 * 每吃一個食物時,就添加在蛇頭,蛇頭往後移動一步,然後蛇身跟著移動。 * 注意:在蛇吃到食物時,要避免捆綁!!! */public class SnakeModel extends Canvas implements ActionListener {private snakePoint[] snakePoint; //裝蛇的數組private static Timer timer; //定時器private static int score = 0; //分數private int Dx, Dy;// 蛇頭所在座標private int Px, Py; //食物的座標static final int LEFT = 1;static final int UP = 2;static final int DOWN = 4;static final int RIGHT = 3;int direction = 4; //初始方向為向下移動boolean isFrist = true; //控制第一個食物的位置boolean isOne = true; //控制每次重新整理一次蛇只能按一次鍵盤boolean food; //控制沒吃到一個食物才去重新整理食物的座標public SnakeModel(int delay) {// 構造蛇模型this.snakePoint = new snakePoint[300]; // 用來裝蛇頭snakePoint[1] = new snakePoint(100, 100);// 畫蛇頭// 使用定時器timer = new Timer(delay, this);timer.start();}public static int getScore() { // 擷取分數return score;}class snakePoint { //蛇身(每條蛇由很多蛇身構成)int x, y;public snakePoint(int x, int y) {this.x = x;this.y = y;}snakePoint(snakePoint p) {this.x = p.x;this.y = p.y;}}@Overridepublic void paint(Graphics g) {//食物creatFood();// 每走一次就讓數組自動移動一次if (score != 0) {for (int i = score + 2; i > 1; i--) {snakePoint[i] = new snakePoint(snakePoint[i - 1]);}}switch (direction) {// 判斷蛇頭的走向case UP:snakePoint[1].y -= 10;break;case DOWN:snakePoint[1].y += 10;break;case LEFT:snakePoint[1].x -= 10;break;case RIGHT:snakePoint[1].x += 10;break;}// 吃到了食物//要考慮食物的座標不可能與蛇頭座標重合if (snakePoint[1].x <= Px + 7 && snakePoint[1].x >= Px - 5&& snakePoint[1].y <= Py + 7 && snakePoint[1].y >= Py - 5) {score++; // 分數加一food = true; // 重新整理食物SnakeMain.re(); // 重新整理分數timer.setDelay((timer.getDelay() - 4) <= 0 ? 20: timer.getDelay() - 4); //每次吃到食物後就會加速蛇的移動速度// System.out.println(timer.getDelay());// 吃掉一個食物後,在蛇頭增加一個長度for (int j = score + 1; j > 1; j--) {snakePoint[j] = new snakePoint(snakePoint[j - 1]);}// 讓蛇頭往移動方向走一步switch (direction) {// 判斷蛇頭的走向case UP:snakePoint[1].y -= 10;break;case DOWN:snakePoint[1].y += 10;break;case LEFT:snakePoint[1].x -= 10;break;case RIGHT:snakePoint[1].x += 10;break;}}g.setColor(Color.RED);//食物為紅色g.fillRect(Px, Py, 10, 10);// 畫食物g.setColor(Color.BLACK);//蛇為黑色// 畫蛇,把蛇從數組中畫出來for (int i = 1; i <= score + 1; i++) {g.fillRect(snakePoint[i].x, snakePoint[i].y, 10, 10);}}private void creatFood() {if (isFrist) {Px = legal(380);// 獲得合法的x值,Py = legal(330);// 獲得合法的y值,即與x組合成食物座標後不在蛇身上isFrist = false;return;}// 下一個食物座標if (food) {Px = legal(380);//同上Py = legal(330);food = false;}// System.out.println(Px);// System.out.println(Py);}private int legal(int i) {Random r = new Random(); //產生隨機數if (i == 380) { //產生食物的y座標while (true) {int n = (r.nextInt(37) + 1) * 10;for (int j = 1; j <= score + 1; j++) { //每次都要與蛇身進行匹配,避免食物出現在蛇身上;下同if (snakePoint[j].x != n && j == (score + 1)) {return n;}}}}if (i == 330) { //產生食物的x座標while (true) {int n = (r.nextInt(32) + 1) * 10;for (int j = 1; j <= score + 1; j++) {if (snakePoint[j].y != n && j == (score + 1)) {return n;}}}}return 0;}@Overridepublic void actionPerformed(ActionEvent e) {isOver();// 判斷是否結束遊戲repaint();isOne = true;// System.out.println(snakePoint[1].x+" "+snakePoint[1].y);}private void isOver() {if (isCondition()) {// isCondition()//判斷是否結束的所有條件放在裡面timer.stop();SnakeMain.gameOver(); // 遊戲結束,彈出對話方塊}}private boolean isCondition() { //遊戲結束的條件// 出界(撞牆)if (snakePoint[1].x <= 0 || snakePoint[1].x >= 380|| snakePoint[1].y <= 0 || snakePoint[1].y >= 330) {return true;}//蛇頭吃到蛇身了for (int i = 2; i <= score + 1; i++) {if (snakePoint[1].x == snakePoint[i].x&& snakePoint[1].y == snakePoint[i].y) {return true;}}return false;}public void changeDirection(int newDirection) { // 改變方向if (direction % 2 != newDirection % 2 && isOne) {// 改變的方向不能與原來的方向相同或相反direction = newDirection;isOne = false;}}public static void stop() {timer.stop();}public static void start() {timer.start();}//重設所有的資料public void reStart(){score=0;direction = 4;isFrist = true;isOne = true;food=false;//snakePoint=null;snakePoint[1].x=100;snakePoint[1].y=100;creatFood();timer.start();}}
class SnakeMain 代碼:
<pre name="code" class="java">import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;public class SnakeMain extends JFrame implements ActionListener {private static JTextField scoreField;private JButton stop,start;public static void main(String[] args) {new SnakeMain();}public SnakeMain() {super("貪吃蛇");this.setBounds(300, 100, 400, 400);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setResizable(false);JPanel p = new JPanel();this.getContentPane().add(p, "North");p.add(new JLabel("Score:"));scoreField = new JTextField("0", 5);scoreField.setEditable(false);stop = new JButton("stop");start = new JButton("start");// 讓這些組件丟失焦點scoreField.setFocusable(false);stop.setFocusable(false);start.setFocusable(false); //添加組件到面板pp.add(scoreField);p.add(stop);p.add(start);SnakeModel snake = new SnakeModel(400);// 500為重新整理時間this.getContentPane().add(snake); // 把蛇加入到面板中 (蛇的運行範圍:0<=x<=380// 0<=y<=330)Control control = new Control(snake); // 控制蛇// 進行監聽stop.addActionListener(this);start.addActionListener(this);this.addKeyListener(control);// 顯示this.setVisible(true);}public static void re() { // 重新整理分數框scoreField.setText("" + SnakeModel.getScore());}public static void gameOver() {// 遊戲結束JOptionPane.showMessageDialog(null, "Game Over!!!");}@Overridepublic void actionPerformed(ActionEvent e) {if (e.getSource() == stop) { SnakeModel.stop();}if (e.getSource() == start) {SnakeModel.start();}}}
貪吃蛇java小程式