没事儿干,用java写了个贪食蛇

没事儿干,用java写了个贪食蛇

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class SnakeGame extends JPanel implements ActionListener {
    static final int SCREEN_WIDTH = 600;
    static final int SCREEN_HEIGHT = 600;
    static final int UNIT_SIZE = 25;
    static final int GAME_UNITS = (SCREEN_WIDTH * SCREEN_HEIGHT) / UNIT_SIZE;
    final int x[] = new int[GAME_UNITS];
    final int y[] = new int[GAME_UNITS];
    java.util.Random random = new java.util.Random();
    int bodyParts = 6;
    int applesEaten;
    int appleX = random.nextInt(SCREEN_WIDTH / UNIT_SIZE) * UNIT_SIZE;
    int appleY = random.nextInt(SCREEN_HEIGHT / UNIT_SIZE) * UNIT_SIZE;
    char direction = 'R';
    boolean running = true;

    SnakeGame() {
        this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
        this.setFocusable(true);
        this.addKeyListener(new MyKeyAdapter());
        new Timer(150, this).start();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        String text = running ? "Score: " + applesEaten + " | ruzhila.cn" : "Game Over";
        if (running) {
            g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
            g.setColor(Color.green);
            for (int i = 0; i < bodyParts; i++) {
                g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
            }
        }
        g.setColor(running ? Color.blue : Color.red);
        g.setFont(new Font("Ink Free", Font.BOLD, 40));
        g.drawString(text, (SCREEN_WIDTH - getFontMetrics(g.getFont()).stringWidth(text)) / 2, g.getFont().getSize());
    }

    public void move() {
        for (int i = bodyParts; i > 0; i--) {
            x[i] = x[(i - 1)];
            y[i] = y[(i - 1)];
        }
        if (direction == 'U') {
            y[0] -= UNIT_SIZE;
        } else if (direction == 'D') {
            y[0] += UNIT_SIZE;
        } else if (direction == 'L') {
            x[0] -= UNIT_SIZE;
        } else if (direction == 'R') {
            x[0] += UNIT_SIZE;
        }
    }

    public class MyKeyAdapter extends KeyAdapter {
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if (keyCode == KeyEvent.VK_LEFT && direction != 'R') {
                direction = 'L';
            } else if (keyCode == KeyEvent.VK_RIGHT && direction != 'L') {
                direction = 'R';
            } else if (keyCode == KeyEvent.VK_UP && direction != 'D') {
                direction = 'U';
            } else if (keyCode == KeyEvent.VK_DOWN && direction != 'U') {
                direction = 'D';
            }
        }
    }

    public void actionPerformed(ActionEvent e) {
        if (running) {
            move();
            if ((x[0] == appleX) && (y[0] == appleY)) {
                applesEaten++;
                bodyParts++;
                appleX = random.nextInt(SCREEN_WIDTH / UNIT_SIZE) * UNIT_SIZE;
                appleY = random.nextInt(SCREEN_HEIGHT / UNIT_SIZE) * UNIT_SIZE;
            }
            for (int i = bodyParts; i > 0; i--) {
                if ((x[0] == x[i]) && (y[0] == y[i])) {
                    running = false;
                    break;
                }
            }
            if (x[0] < 0 || x[0] > SCREEN_WIDTH || y[0] < 0 || y[0] > SCREEN_HEIGHT) {
                running = false;
            }
        }
        repaint();
    }


    // ...
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new SnakeGame());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}
  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的贪食蛇游戏,使用Java。它包括一个游戏循环,可以处理用户输入,更新游戏状态并绘制游戏画面。 ```java import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class SnakeGame extends JFrame implements ActionListener { private static final int WIDTH = 500; private static final int HEIGHT = 500; private static final int DOT_SIZE = 20; private static final int ALL_DOTS = (WIDTH * HEIGHT) / (DOT_SIZE * DOT_SIZE); private static final int RAND_POS = WIDTH / DOT_SIZE; private static final int DELAY = 100; private ArrayList<Point> snake; private Point food; private Timer timer; private boolean inGame; private boolean leftDirection; private boolean rightDirection; private boolean upDirection; private boolean downDirection; public SnakeGame() { setTitle("Snake Game"); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); setVisible(true); addKeyListener(new TAdapter()); snake = new ArrayList<Point>(); inGame = true; leftDirection = false; rightDirection = true; upDirection = false; downDirection = false; initGame(); } public void initGame() { snake.clear(); snake.add(new Point(100, 100)); snake.add(new Point(80, 100)); snake.add(new Point(60, 100)); generateFood(); timer = new Timer(DELAY, this); timer.start(); } public void generateFood() { int x = (int) (Math.random() * RAND_POS) * DOT_SIZE; int y = (int) (Math.random() * RAND_POS) * DOT_SIZE; food = new Point(x, y); } public void checkFood() { if (snake.get(0).equals(food)) { snake.add(0, new Point(food)); generateFood(); } } public void checkCollision() { for (int i = 1; i < snake.size(); i++) { if (snake.get(0).equals(snake.get(i))) { inGame = false; } } if (snake.get(0).x < 0 || snake.get(0).x >= WIDTH || snake.get(0).y < 0 || snake.get(0).y >= HEIGHT) { inGame = false; } if (!inGame) { timer.stop(); } } public void move() { for (int i = snake.size() - 1; i > 0; i--) { snake.set(i, new Point(snake.get(i-1))); } if (leftDirection) { snake.get(0).x -= DOT_SIZE; } else if (rightDirection) { snake.get(0).x += DOT_SIZE; } else if (upDirection) { snake.get(0).y -= DOT_SIZE; } else if (downDirection) { snake.get(0).y += DOT_SIZE; } } public void paint(Graphics g) { super.paint(g); if (inGame) { g.setColor(Color.RED); g.fillOval(food.x, food.y, DOT_SIZE, DOT_SIZE); g.setColor(Color.BLACK); for (Point p : snake) { g.fillOval(p.x, p.y, DOT_SIZE, DOT_SIZE); } Toolkit.getDefaultToolkit().sync(); } else { gameOver(g); } } public void gameOver(Graphics g) { String msg = "Game Over"; Font font = new Font("Arial", Font.BOLD, 16); FontMetrics metrics = getFontMetrics(font); g.setColor(Color.BLACK); g.setFont(font); g.drawString(msg, (WIDTH - metrics.stringWidth(msg)) / 2, HEIGHT / 2); } public void actionPerformed(ActionEvent e) { if (inGame) { checkFood(); checkCollision(); move(); repaint(); } } private class TAdapter extends KeyAdapter { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT && !rightDirection) { leftDirection = true; upDirection = false; downDirection = false; } else if (key == KeyEvent.VK_RIGHT && !leftDirection) { rightDirection = true; upDirection = false; downDirection = false; } else if (key == KeyEvent.VK_UP && !downDirection) { upDirection = true; leftDirection = false; rightDirection = false; } else if (key == KeyEvent.VK_DOWN && !upDirection) { downDirection = true; leftDirection = false; rightDirection = false; } } } public static void main(String[] args) { new SnakeGame(); } } ``` 这个游戏使用Java Swing库来处理窗口和绘制。它使用一个ArrayList来跟踪蛇的身体,一个Point来表示食物的位置,以及一些布尔变量来跟踪蛇的方向。游戏循环在ActionListener中实现,并在每个时钟周期中更新游戏状态并重新绘制游戏画面。键盘事件处理程序允许玩家使用箭头键来控制蛇的移动。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值