帮我写一个Java贪吃蛇游戏出来
时间: 2023-03-07 10:07:16 浏览: 114
我已经为您准备了一个Java贪吃蛇游戏的代码:import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;public class SnakeGame extends JPanel implements KeyListener, ActionListener{int lengthOfSnake = 3;
int score = 0;
int[] snakeXlength = new int[750];
int[] snakeYlength = new int[750];
boolean left = false;
boolean right = false;
boolean up = false;
boolean down = false;
Timer timer;
int delay = 100;
int moves = 0;public SnakeGame() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);
timer.start();
}public void paint(Graphics g) {
if (moves == 0) {
snakeXlength[2] = 50;
snakeXlength[1] = 75;
snakeXlength[0] = 100;
snakeYlength[2] = 100;
snakeYlength[1] = 100;
snakeYlength[0] = 100;
} //draw title
g.setColor(Color.white);
g.drawString("Score : " + score, 250, 50); //draw snake
for (int i = 0; i < lengthOfSnake; i++) {
if (i == 0) {
g.setColor(Color.GREEN);
g.fillRect(snakeXlength[i], snakeYlength[i], 20, 20);
} else {
g.fillRect(snakeXlength[i], snakeYlength[i], 20, 20);
}
} //draw boundary
g.setColor(Color.white);
g.drawRect(50, 50, 350, 350); timer.start();
}public static void main(String[] args) {
JFrame frame = new JFrame();
SnakeGame game = new SnakeGame();
frame.add(game);
frame.setBounds(400, 100, 500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setTitle("Snake Game");
}@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub}@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub}@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub}@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub}
}我希望这个代码能够帮助您完成您的Java贪吃蛇游戏。
阅读全文