开发者代码

促销活动、技术干货、问题解答、技术讨论,学习,成长,分享,共建

贪吃蛇java代码完整版

2023-11-30 08:14:42 点击:70
贪吃蛇java代码完整版
下面是一个简单的贪吃蛇的Java代码示例:


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


public class SnakeGame extends JFrame {


private final int WIDTH = 300; private final int HEIGHT = 300; private final int DOT_SIZE = 10; private final int ALL_DOTS = WIDTH * HEIGHT / (DOT_SIZE * DOT_SIZE); private final int RAND_POS = 29; private final int DELAY = 140;


private final int x[] = new int[ALL_DOTS]; private final int y[] = new int[ALL_DOTS];


private int dots; private int apple_x; private int apple_y;


private Timer timer; private boolean inGame = true;


public SnakeGame() { initGame(); initUI(); }


private void initGame() { dots = 3;


for (int i = 0; i < dots; i++) { x[i] = 50 - i * DOT_SIZE; y[i] = 50; }


locateApple();


timer = new Timer(DELAY, new ActionListener() { public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); }


repaint(); } }); timer.start(); }


private void initUI() { setTitle("Snake"); setSize(WIDTH, HEIGHT); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null);


Board board = new Board(); add(board);


addKeyListener(new TAdapter());


addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent e) { requestFocus(); } }); }


private void locateApple() { int r = (int) (Math.random() * RAND_POS); apple_x = ((r * DOT_SIZE));


r = (int) (Math.random() * RAND_POS); apple_y = ((r * DOT_SIZE)); }


private void checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); } }


private void checkCollision() { for (int i = dots; i > 0; i--) { if ((i > 3) && (x[0] == x[i - 1]) && (y[0] == y[i - 1])) { inGame = false; } }


if (y[0] >= HEIGHT || y[0] < 0 || x[0] >= WIDTH || x[0] < 0) { inGame = false; }


if (!inGame) { timer.stop(); } }


private void move() { for (int i = dots; i > 0; i--) { x[i] = x[(i - 1)]; y[i] = y[(i - 1)]; }


if (x[0] < x[dots]) { x[0] += DOT_SIZE; } else if (x[0] > x[dots]) { x[0] -= DOT_SIZE; } else if (y[0] < y[dots]) { y[0] += DOT_SIZE; } else if (y[0] > y[dots]) { y[0] -= DOT_SIZE; } }


public class Board extends JPanel {


@Override protected void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); }


private void doDrawing(Graphics g) { if (inGame) { g.setColor(Color.red); g.fillOval(apple_x, apple_y, DOT_SIZE, DOT_SIZE);


for (int i = 0; i < dots; i++) { if (i == 0) { g.setColor(Color.green); } else { g.setColor(Color.black); } g.fillRect(x[i], y[i], DOT_SIZE, DOT_SIZE); }


Toolkit.getDefaultToolkit().sync(); } else { gameOver(g); } }


private void gameOver(Graphics g) { String msg = "Game Over"; Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small);


g.setColor(Color.black); g.setFont(small); g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2); } }


private class TAdapter extends KeyAdapter {


@Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode();


if ((key == KeyEvent.VK_LEFT) && (!inGame)) { inGame = true; initGame(); }


if ((key == KeyEvent.VK_RIGHT) && (!inGame)) { inGame = true; initGame(); }


if ((key == KeyEvent.VK_UP) && (!inGame)) { inGame = true; initGame(); }


if ((key == KeyEvent.VK_DOWN) && (!inGame)) { inGame = true; initGame(); }


if ((key == KeyEvent.VK_LEFT) && (x[0] != x[dots])) { x[0] -= DOT_SIZE; }


if ((key == KeyEvent.VK_RIGHT) && (x[0] != x[dots])) { x[0] += DOT_SIZE; }


if ((key == KeyEvent.VK_UP) && (y[0] != y[dots])) { y[0] -= DOT_SIZE; }


if ((key == KeyEvent.VK_DOWN) && (y[0] != y[dots])) { y[0] += DOT_SIZE; } } }


public static void main(String[] args) { EventQueue.invokeLater(() -> { SnakeGame ex = new SnakeGame(); ex.setVisible(true); }); } } ```


此代码使用Java的Swing库和AWT库来实现一个简单的贪吃蛇游戏。游戏的主要逻辑位于`initGame()`方法中,它初始化蛇的位置、苹果的位置和定时器。`move()`方法用于更新蛇的位置,`checkCollision()`方法用于检查蛇是否与边界或自身发生碰撞。`checkApple()`方法在蛇吃到苹果时增加蛇的长度,并重新生成一个苹果。游戏的界面通过`Board`类中的`paintComponent()`方法来绘制。用户可以通过键盘的方向键控制蛇的移动方向。


希望这段代码能帮助你理解如何实现一个简单的贪吃蛇游戏。如果有任何问题,请随时向我提问。
声明:免责声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,也不承认相关法律责任。如果您发现本社区中有涉嫌抄袭的内容,请发送邮件至:dm@cn86.cn进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。本站原创内容未经允许不得转载。
  • 7x24

    在线售后支持

  • 10

    +

    10年互联网服务经验

  • 300

    +

    全国300余家服务机构

  • 70000

    +

    与70000余家企业客户携手

logo
祥云平台主营业务:品牌型网站建设,高端型网站建设, 外贸型网站建设,营销型网站建设,网站优化, 开发类网站,企业网络营销,搜索引擎推广,微信小程序, 企业邮箱,短视频运营等。

服务热线

400-007-8608

公司:

苏州祥云平台信息技术有限公司
苏州华企立方信息技术有限公司

地址:江苏省昆山市昆太路530号祥和国际大厦15-16层

返回顶部