当前位置:   article > 正文

java贪吃蛇源代码_java贪吃蛇源代码详解

java贪吃蛇代码总结

1、本代码主要功能为实现贪吃蛇游戏,GUI界面做到尽量简洁和原游戏相仿。目前版本包含计分,统计最高分,长度自动缩短计时功能。

2、运行时请把.java文件放入default package 即可运行。

a)文件位置

22060acf5ec533343d5167d4de383372.png

b)进入游戏

876592f56d3c6722eb5a5413bdaaed1a.png

c) 游戏进行中

02a4b577ecad1bda4b5c9eb63d4b3868.png

JAVA实现代码

ALL RIGHTS RESERVED 3 import java.awt.*;

import java.awt.event.*;

importstaTIc java.lang.String.format; import java.uTIl.*;

import java.uTIl.List; import javax.swing.*;

Publicclass Snakeextends JPanel implements Runnable {

enum Dir {

up(0, -1), right(1, 0), down(0, 1), left(-1, 0);

Dir(intx, inty) { this.x = x; this.y = y;

}

finalintx, y;

}

staTIcfinal Random rand = new Random();

staticfinalintWALL = -1;

staticfinalintMAX_ENERGY = 1500;

volatilebooleangameOver = true;

Thread gameThread; intscore, hiScore; intnRows = 44;

intnCols = 64;

Dir dir; intenergy;

int[][] grid;

List《Point>snake, treats;

Font smallFont;

public Snake() {

setPreferredSize(new Dimension(640, 440));

setBackground(Color.white);

setFont(new Font(“SansSerif”, Font.BOLD, 48));

setFocusable(true);

smallFont = getFont().deriveFont(Font.BOLD, 18);

initGrid();

addMouseListener(new MouseAdapter() {

@Override

publicvoid mousePressed(MouseEvent e) {

if (gameOver) {

startNewGame();

repaint();

}

}

});

addKeyListener(new KeyAdapter() {

@Override

publicvoid keyPressed(KeyEvent e) {

switch (e.getKeyCode()) {

case KeyEvent.VK_UP: if (dir != Dir.down) dir = Dir.up; break;

case KeyEvent.VK_LEFT: if (dir != Dir.right) dir = Dir.left; break;

case KeyEvent.VK_RIGHT: if (dir != Dir.left) dir = Dir.right; break;

case KeyEvent.VK_DOWN: if (dir != Dir.up) dir = Dir.down; break;

}

repaint();

}

});

}

void startNewGame() { gameOver = false;

stop();

initGrid();

treats = new LinkedList<>();

dir = Dir.left;

energy = MAX_ENERGY;

if (score>hiScore) hiScore = score; score = 0;

snake = new ArrayList<>(); for (intx = 0; x< 7; x++) snake.add(new Point(nCols / 2 + x, nRows / 2));

do addTreat(); while(treats.isEmpty());

(gameThread = new Thread(this)).start();

}

void stop() {

if (gameThread != null) {

Thread tmp = gameThread; gameThread = null; tmp.interrupt();

}

}

void initGrid() { grid = newint[nRows][nCols]; for (intr = 0;

r《nRows; r++) { for (intc = 0; c

if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1) grid[r][c] = WALL;

}

}

}

@Override

publicvoid run() {

while (Thread.currentThread() == gameThread) { try { Thread.sleep(Math.max(75 - score, 25));

} catch (InterruptedException e) {

return;

} if (energyUsed() || hitsWall() || hitsSnake()) {

gameOver();

} else {

if (eatsTreat()) { score++; energy = MAX_ENERGY;

growSnake();

}

moveSnake();

addTreat();

}

repaint();

}

} boolean energyUsed() { energy -= 10;

returnenergy<= 0;

}

boolean hitsWall() {

Point head = snake.get(0);

intnextCol = head.x + dir.x;

intnextRow = head.y + dir.y;

returngrid[nextRow][nextCol] == WALL;

}

boolean hitsSnake() {

Point head = snake.get(0);

intnextCol = head.x + dir.x;

intnextRow = head.y + dir.y;

for (Point p : snake) if (p.x == nextCol&&p.y == nextRow) returntrue; returnfalse;

}

boolean eatsTreat() {

Point head = snake.get(0);

intnextCol = head.x + dir.x; intnextRow = head.y + dir.y; for (Point p : treats) if (p.x == nextCol&&p.y == nextRow) { returntreats.remove(p);

}

returnfalse;

} void gameOver() { gameOver = true;

stop();

} void moveSnake() {

for (inti = snake.size() - 1; i> 0; i--) {

Point p1 = snake.get(i - 1);

Point p2 = snake.get(i); p2.x = p1.x;

p2.x = p1.x; p2.y = p1.y;

}

Point head = snake.get(0); head.x += dir.x; head.y += dir.y;

}

void growSnake() {

Point tail = snake.get(snake.size() - 1); intx = tail.x + dir.x; inty = tail.y + dir.y; snake.add(new Point(x, y));

} void addTreat() { if (treats.size() 《 3) {

if (rand.nextInt(10) == 0) { // 1 in 10 if (rand.nextInt(4) != 0) { // 3 in 4 intx, y; while (true) {

x = rand.nextInt(nCols);

y = rand.nextInt(nRows); if (grid[y][x] != 0) continue;

Point p = new Point(x, y);

if (snake.contains(p) || treats.contains(p)) continue;

treats.add(p); break;

}

}

elseif (treats.size() > 1) treats.remove(0);

}

}

}

void drawGrid(Graphics2D g) { g.setColor(Color.lightGray);

for (intr = 0; r

}

}

}

void drawSnake(Graphics2D g) { g.setColor(Color.blue); for (Point p : snake) g.fillRect(p.x * 10, p.y * 10, 10, 10);

g.setColor(energy< 500 ? Color.red : Color.orange);

Point head = snake.get(0);

g.fillRect(head.x * 10, head.y * 10, 10, 10);

}

void drawTreats(Graphics2D g) {

g.setColor(Color.green); for (Point p : treats) g.fillRect(p.x * 10, p.y * 10, 10, 10);}

void drawStartScreen(Graphics2D g) { g.setColor(Color.blue);

g.setFont(getFont());

g.drawString(“Snake”, 240, 190);

g.setColor(Color.orange); g.setFont(smallFont);

g.drawString(“(click to start)”, 250, 240);

}

void drawScore(Graphics2D g) { inth = getHeight();

g.setFont(smallFont);

g.setColor(getForeground());

String s = format(“hiscore %d score %d”, hiScore, score);

g.drawString(s, 30, h - 30);

g.drawString(format(“energy %d”, energy), getWidth() - 150, h - 30);

}

@Override

publicvoid paintComponent(Graphics gg) { super.paintComponent(gg);

Graphics2D g = (Graphics2D) gg;

g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

drawGrid(g);

if (gameOver) {

drawStartScreen(g);

} else {

drawSnake(g);

drawTreats(g);

drawScore(g);

}

}

publicstaticvoid main(String[] args) {

SwingUtilities.invokeLater(() -> {

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setTitle(“Snake”);

f.setResizable(false);

f.add(new Snake(), BorderLayout.CENTER);

f.pack();

f.setLocationRelativeTo(null);

f.setVisible(true);

});

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/699548
推荐阅读
相关标签
  

闽ICP备14008679号