给我写一份贪吃蛇JAVA代码
时间: 2023-03-24 08:00:34 浏览: 239
好的,以下是一份简单的Java代码,用于计算一组数字的总和:
```java
public class SumCalculator {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5}; // 定义一个包含数字的数组
int sum = 0; // 定义一个变量来存储总和
for (int i = 0; i < numbers.length; i++) { // 循环遍历数组中的每个数字
sum += numbers[i]; // 将每个数字加到总和中
}
System.out.println("这组数字的总和是:" + sum); // 输出结果
}
}
```
这段代码将一个包含数字的数组作为输入,并使用循环遍历数组中的每个数字,并将它们加到一个变量中以计算它们的总和。最后,代码将打印出计算出的总和。请注意,这只是一个简单的示例,Java有很多其他用途和功能。
相关问题
帮我用Java写一套贪吃蛇代码
好的,以下是一份简单的Java贪吃蛇代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame implements ActionListener {
private final int WIDTH = 300;
private final int HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
private int x[] = new int[ALL_DOTS];
private int y[] = new int[ALL_DOTS];
private int dots;
private int apple_x;
private int apple_y;
private boolean leftDirection = false;
private boolean rightDirection = true;
private boolean upDirection = false;
private boolean downDirection = false;
private boolean inGame = true;
private Timer timer;
private Image ball;
private Image apple;
private Image head;
public SnakeGame() {
setTitle("Snake");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
ImageIcon iid = new ImageIcon(getClass().getResource("dot.png"));
ball = iid.getImage();
ImageIcon iia = new ImageIcon(getClass().getResource("apple.png"));
apple = iia.getImage();
ImageIcon iih = new ImageIcon(getClass().getResource("head.png"));
head = iih.getImage();
addKeyListener(new TAdapter());
initGame();
}
private void initGame() {
dots = 3;
for (int z = 0; z < dots; z++) {
x[z] = 50 - z * 10;
y[z] = 50;
}
locateApple();
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(ball, x[z], y[z], this);
}
}
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.white);
g.setFont(small);
g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2);
}
private void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateApple();
}
}
private void move() {
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (leftDirection) {
x[0] -= DOT_SIZE;
}
if (rightDirection) {
x[0] += DOT_SIZE;
}
if (upDirection) {
y[0] -= DOT_SIZE;
}
if (downDirection) {
y[0] += DOT_SIZE;
}
}
private void checkCollision() {
for (int z = dots; z > 0; z--) {
if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
inGame = false;
}
}
if (y[0] >= HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
if (!inGame) {
timer.stop();
}
}
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));
}
@Override
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
private class TAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
leftDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
rightDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_UP) && (!downDirection)) {
upDirection = true;
rightDirection = false;
leftDirection = false;
}
if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
}
public static void main(String[] args) {
new SnakeGame().setVisible(true);
}
}
```
希望这份代码能够帮到你!
Java编写贪吃蛇的代码
### 回答1:
以下是一份简单的 Java 代码实现贪吃蛇游戏的示例:
```
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class SnakeGame implements ActionListener, KeyListener {
public static SnakeGame snake;
public JFrame jframe;
public RenderPanel renderPanel;
public Timer timer = new Timer(20, this);
public ArrayList<Point> snakeParts = new ArrayList<Point>();
public static final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3, SCALE = 10;
public int ticks = 0, direction = DOWN, score, tailLength = 10, time;
public Point head, cherry;
public Random random;
public boolean over = false, paused;
public Dimension dim;
public SnakeGame() {
dim = Toolkit.getDefaultToolkit().getScreenSize();
jframe = new JFrame("Snake Game");
jframe.setVisible(true);
jframe.setSize(805, 700);
jframe.setResizable(false);
jframe.setLocation(dim.width / 2 - jframe.getWidth() / 2, dim.height / 2 - jframe.getHeight() / 2);
jframe.add(renderPanel = new RenderPanel());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.addKeyListener(this);
startGame();
}
public void startGame() {
over = false;
paused = false;
time = 0;
score = 0;
tailLength = 14;
direction = DOWN;
head = new Point(0, -1);
random = new Random();
snakeParts.clear();
cherry = new Point(random.nextInt(79), random.nextInt(66));
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
renderPanel.repaint();
ticks++;
if (ticks % 2 == 0 && head != null && !over && !paused) {
time++;
snakeParts.add(new Point(head.x, head.y));
if (snakeParts.size() > tailLength) {
snakeParts.remove(0);
}
if (direction == UP) {
if (head.y - 1 >= 0 && noTailAt(head.x, head.y - 1)) {
head = new
### 回答2:
贪吃蛇是一款经典的游戏,以下是使用Java编写贪吃蛇的代码示例:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GreedySnake extends JFrame {
private static final int WIDTH = 400; // 窗口宽度
private static final int HEIGHT = 400; // 窗口高度
private int snakeSize; // 蛇的大小
private int snakeX; // 蛇头的横坐标
private int snakeY; // 蛇头的纵坐标
private int foodX; // 食物的横坐标
private int foodY; // 食物的纵坐标
public GreedySnake() {
setTitle("Greedy Snake"); // 设置窗口标题
setSize(WIDTH, HEIGHT); // 设置窗口大小
setLocationRelativeTo(null); // 将窗口居中显示
setResizable(false); // 禁止窗口大小调整
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
snakeSize = 3;
snakeX = 20; snakeY = 20; // 初始蛇头位置
foodX = 100; foodY = 100; // 初始食物位置
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// 根据按键设置蛇头的位置
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
snakeY -= 10;
break;
case KeyEvent.VK_DOWN:
snakeY += 10;
break;
case KeyEvent.VK_LEFT:
snakeX -= 10;
break;
case KeyEvent.VK_RIGHT:
snakeX += 10;
break;
}
repaint(); // 更新界面显示
}
});
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(snakeX, snakeY, 10, 10); // 绘制蛇头
g.setColor(Color.RED);
g.fillRect(foodX, foodY, 10, 10); // 绘制食物
}
public static void main(String[] args) {
GreedySnake snake = new GreedySnake();
snake.setVisible(true); // 显示游戏窗口
}
}
```
这段代码通过`JFrame`类实现了贪吃蛇游戏的窗口界面,并使用`KeyListener`监听键盘按键事件来控制游戏。在`paint`方法中,使用`Graphics`类的相关方法绘制蛇头和食物的位置。在`main`方法中,创建了一个`GreedySnake`对象,并将其设为可见,从而启动游戏窗口。在窗口中,按上下左右箭头键可以控制蛇头的移动。
### 回答3:
贪吃蛇是一款经典的游戏,以下是一个简单的Java代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame {
private Snake snake;
private Timer timer;
private final int DELAY = 100;
public SnakeGame() {
snake = new Snake();
initUI();
initGame();
}
private void initUI() {
setTitle("贪吃蛇");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
add(snake);
pack();
setLocationRelativeTo(null);
}
private void initGame() {
timer = new Timer(DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
snake.move();
repaint();
}
});
timer.start();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
SnakeGame game = new SnakeGame();
game.setVisible(true);
});
}
}
class Snake extends JPanel {
private final int DOT_SIZE = 10;
private final int BOARD_SIZE = 300;
private final int TOTAL_DOTS = (BOARD_SIZE * BOARD_SIZE) / (DOT_SIZE * DOT_SIZE);
private final int[] x = new int[TOTAL_DOTS];
private final int[] y = new int[TOTAL_DOTS];
private int dots;
private int appleX;
private int appleY;
private boolean isMovingLeft;
private boolean isMovingRight;
private boolean isMovingUp;
private boolean isMovingDown;
public Snake() {
setPreferredSize(new Dimension(BOARD_SIZE, BOARD_SIZE));
setBackground(Color.black);
setFocusable(true);
initGame();
addKeyListener(new SnakeKeyListener());
}
private void initGame() {
dots = 3;
for (int i = 0; i < dots; i++) {
x[i] = 50 - i * DOT_SIZE;
y[i] = 50;
}
locateApple();
}
private void locateApple() {
int r = (int) (Math.random() * (BOARD_SIZE / DOT_SIZE));
appleX = r * DOT_SIZE;
r = (int) (Math.random() * (BOARD_SIZE / DOT_SIZE));
appleY = r * DOT_SIZE;
}
private void checkCollision() {
for (int i = dots - 1; i > 0; i--) {
if (i > 3 && x[0] == x[i] && y[0] == y[i]) {
timer.stop();
}
}
if (y[0] >= BOARD_SIZE || y[0] < 0 || x[0] >= BOARD_SIZE || x[0] < 0) {
timer.stop();
}
}
void move() {
for (int i = dots; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
if (isMovingLeft) {
x[0] -= DOT_SIZE;
}
if (isMovingRight) {
x[0] += DOT_SIZE;
}
if (isMovingUp) {
y[0] -= DOT_SIZE;
}
if (isMovingDown) {
y[0] += DOT_SIZE;
}
checkCollision();
checkApple();
}
private void checkApple() {
if (x[0] == appleX && y[0] == appleY) {
dots++;
locateApple();
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
private void draw(Graphics g) {
if (dots > 0) {
g.setColor(Color.green);
g.fillOval(appleX, appleY, DOT_SIZE, DOT_SIZE);
for (int i = 0; i < dots; i++) {
if (i == 0) {
g.setColor(Color.white);
g.fillRect(x[i], y[i], DOT_SIZE, DOT_SIZE);
} else {
g.setColor(Color.green);
g.fillRect(x[i], y[i], DOT_SIZE, DOT_SIZE);
}
}
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String msg = "Game Over";
Font font = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metrics = getFontMetrics(font);
g.setColor(Color.white);
g.setFont(font);
g.drawString(msg, (BOARD_SIZE - metrics.stringWidth(msg)) / 2, BOARD_SIZE / 2);
}
private class SnakeKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT && !isMovingRight) {
isMovingLeft = true;
isMovingUp = false;
isMovingDown = false;
} else if (key == KeyEvent.VK_RIGHT && !isMovingLeft) {
isMovingRight = true;
isMovingUp = false;
isMovingDown = false;
} else if (key == KeyEvent.VK_UP && !isMovingDown) {
isMovingUp = true;
isMovingLeft = false;
isMovingRight = false;
} else if (key == KeyEvent.VK_DOWN && !isMovingUp) {
isMovingDown = true;
isMovingLeft = false;
isMovingRight = false;
}
}
}
}
```
这段代码使用Java的Swing库创建了一个简单的窗口,并在窗口内绘制了一个贪吃蛇游戏。Snake类是一个面板,它处理游戏逻辑和绘制。SnakeGame类是游戏的主类,它创建了窗口并初始化游戏。
Snake类包括一些变量来跟踪贪吃蛇的位置、苹果的位置以及游戏状态。它使用定时器来控制贪吃蛇的移动,并根据用户的按键输入来改变运动方向。游戏结束时,它会在屏幕上显示“Game Over”消息。
请注意,这只是一个简单的示例代码,实际的贪吃蛇游戏可能包含更多功能和复杂性。
阅读全文