写一段贪食蛇的Java代码
时间: 2024-05-10 20:18:36 浏览: 9
以下是一个简单的贪食蛇Java代码示例:
```java
import java.util.ArrayList;
import java.util.Random;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SnakeGame extends Application {
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private static final int TILE_SIZE = 10;
private static final Color SNAKE_COLOR = Color.GREEN;
private static final Color FOOD_COLOR = Color.RED;
private static final Random rand = new Random();
private ArrayList<Position> snake;
private Position food;
private Direction direction;
private boolean gameOver = false;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
Canvas canvas = new Canvas(WIDTH, HEIGHT);
GraphicsContext gc = canvas.getGraphicsContext2D();
Label scoreLabel = new Label("Score: 0");
BorderPane root = new BorderPane(canvas, null, null, scoreLabel, null);
Scene scene = new Scene(root, WIDTH, HEIGHT);
// Initialize game
snake = new ArrayList<>();
snake.add(new Position(WIDTH / 2, HEIGHT / 2));
spawnFood();
direction = Direction.NONE;
// Handle input
scene.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.UP && direction != Direction.DOWN) {
direction = Direction.UP;
} else if (e.getCode() == KeyCode.DOWN && direction != Direction.UP) {
direction = Direction.DOWN;
} else if (e.getCode() == KeyCode.LEFT && direction != Direction.RIGHT) {
direction = Direction.LEFT;
} else if (e.getCode() == KeyCode.RIGHT && direction != Direction.LEFT) {
direction = Direction.RIGHT;
}
});
// Game loop
new AnimationTimer() {
private long lastUpdate = 0;
private int score = 0;
@Override
public void handle(long now) {
if (now - lastUpdate >= 100_000_000) { // Update every 100ms
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, WIDTH, HEIGHT);
// Move snake
if (!gameOver) {
moveSnake();
}
// Draw snake
gc.setFill(SNAKE_COLOR);
for (Position pos : snake) {
gc.fillRect(pos.getX(), pos.getY(), TILE_SIZE, TILE_SIZE);
}
// Draw food
gc.setFill(FOOD_COLOR);
gc.fillRect(food.getX(), food.getY(), TILE_SIZE, TILE_SIZE);
// Check for collision with food
if (snake.get(0).equals(food)) {
snake.add(new Position(-TILE_SIZE, -TILE_SIZE)); // Add new segment off-screen
spawnFood();
score++;
scoreLabel.setText("Score: " + score);
}
// Check for collision with walls or self
if (snake.get(0).getX() < 0 || snake.get(0).getX() >= WIDTH ||
snake.get(0).getY() < 0 || snake.get(0).getY() >= HEIGHT ||
checkCollisionWithSelf()) {
gameOver = true;
gc.setFill(Color.BLACK);
gc.fillText("Game Over!", WIDTH / 2 - 30, HEIGHT / 2);
}
lastUpdate = now;
}
}
}.start();
stage.setScene(scene);
stage.setTitle("Snake Game");
stage.show();
}
private void moveSnake() {
// Move each segment of the snake
for (int i = snake.size() - 1; i > 0; i--) {
snake.get(i).setX(snake.get(i - 1).getX());
snake.get(i).setY(snake.get(i - 1).getY());
}
// Move head of snake in correct direction
if (direction == Direction.UP) {
snake.get(0).setY(snake.get(0).getY() - TILE_SIZE);
} else if (direction == Direction.DOWN) {
snake.get(0).setY(snake.get(0).getY() + TILE_SIZE);
} else if (direction == Direction.LEFT) {
snake.get(0).setX(snake.get(0).getX() - TILE_SIZE);
} else if (direction == Direction.RIGHT) {
snake.get(0).setX(snake.get(0).getX() + TILE_SIZE);
}
}
private void spawnFood() {
// Choose a random position for the food
int x = rand.nextInt(WIDTH / TILE_SIZE) * TILE_SIZE;
int y = rand.nextInt(HEIGHT / TILE_SIZE) * TILE_SIZE;
food = new Position(x, y);
// Make sure food doesn't spawn on top of snake
while (checkCollisionWithSelf()) {
x = rand.nextInt(WIDTH / TILE_SIZE) * TILE_SIZE;
y = rand.nextInt(HEIGHT / TILE_SIZE) * TILE_SIZE;
food.setX(x);
food.setY(y);
}
}
private boolean checkCollisionWithSelf() {
// Check if any part of the snake is on top of the food
for (Position pos : snake) {
if (pos.equals(food)) {
return true;
}
}
// Check if any part of the snake is colliding with itself
for (int i = 1; i < snake.size(); i++) {
if (snake.get(0).equals(snake.get(i))) {
return true;
}
}
return false;
}
}
class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Position) {
Position other = (Position) obj;
return x == other.x && y == other.y;
}
return false;
}
}
enum Direction {
UP, DOWN, LEFT, RIGHT, NONE
}
```
该代码使用JavaFX库实现了一个简单的贪食蛇游戏。其中包含Snake类、Position类和Direction枚举类。Snake类包含主要的游戏逻辑,Position类用于表示游戏中的位置,Direction枚举类用于表示蛇头移动的方向。代码使用Canvas和GraphicsContext绘制游戏界面,并使用AnimationTimer进行游戏循环。整个游戏的逻辑比较简单,可以通过阅读代码来理解。