java射击小游戏代码
时间: 2023-05-18 16:00:29 浏览: 180
java小游戏代码
5星 · 资源好评率100%
Java射击小游戏代码可以通过使用Java编程语言来实现。该游戏的目标是让玩家用一个虚拟的枪击中移动的目标。
以下是可用于实现Java射击小游戏的代码示例:
/**
* 射击游戏 - Java代码示例
*/
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JFrame;
public class ShootingGame extends JFrame {
private static final long serialVersionUID = 1470871033156271241L;
private static final int WIDTH = 600;
private static final int HEIGHT = 400;
private BufferedImage buffer;
private Graphics bufferGraphics;
private Random random = new Random();
private int score;
public ShootingGame() {
setTitle("Shooting Game");
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
buffer = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
bufferGraphics = buffer.getGraphics();
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
bufferGraphics.clearRect(0, 0, WIDTH, HEIGHT);
bufferGraphics.drawString("Score: " + score, WIDTH - 100, 20);
bufferGraphics.fillRect(e.getX() - 10, 360, 20, 20);
repaint();
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int targetX = random.nextInt(WIDTH);
int targetY = random.nextInt(300);
if (e.getY() >= targetY && e.getY() <= targetY + 40) {
score++;
}
bufferGraphics.clearRect(0, 0, WIDTH, HEIGHT);
bufferGraphics.drawString("Score: " + score, WIDTH - 100, 20);
bufferGraphics.fillRect(e.getX() - 10, 360, 20, 20);
bufferGraphics.fillRect(targetX - 10, targetY, 20, 40);
repaint();
}
});
}
@Override
public void paint(Graphics g) {
g.drawImage(buffer, 0, 0, this);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new ShootingGame();
});
}
}
以上代码中,我们创建了一个扩展了JFrame类的ShootingGame类,并在其中定义了游戏的主要游戏逻辑。随机的目标从屏幕的顶部向下移动,玩家需要在正确的时间射击目标以增加得分。在游戏的过程中,我们还记录玩家的分数,并在屏幕上显示。这段代码包括自定义的绘图和鼠标事件处理功能,以便将游戏显示在屏幕上,并接受玩家的输入。通过使用Java编写此类代码,我们可以构建一个简单而有趣的射击游戏,让用户积极参与。
阅读全文