帮我写一个基于Java的飞行棋小游戏并且实习界面化
时间: 2023-03-20 09:01:38 浏览: 181
很高兴为您提供帮助,以下是一个基于Java的简单飞行棋小游戏示例代码:
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FlyChess extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private JPanel panel;
private JButton startBtn, rollBtn;
private Image[] images;
private int currentPos;
private Random random;
public FlyChess() {
setTitle("飞行棋小游戏");
setSize(600, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
initPanel();
add(panel);
setVisible(true);
}
private void initPanel() {
panel = new JPanel() {
private static final long serialVersionUID = 1L;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(images[0], 0, 0, null);
for(int i = 1; i <= 4; i++) {
int x = (i-1)*100+70;
int y = 290;
g.drawImage(images[i], x, y, null);
if(currentPos == i) {
g.setColor(Color.RED);
g.fillOval(x+30, y+30, 40, 40);
}
}
}
};
panel.setLayout(null);
images = new Image[5];
for(int i = 0; i < 5; i++) {
images[i] = new ImageIcon(getClass().getResource("/image/" + i + ".png")).getImage();
}
startBtn = new JButton("开始游戏");
startBtn.setBounds(50, 50, 100, 30);
startBtn.addActionListener(this);
panel.add(startBtn);
rollBtn = new JButton("掷骰子");
rollBtn.setBounds(200, 50, 100, 30);
rollBtn.addActionListener(this);
panel.add(rollBtn);
random = new Random();
}
private void startGame() {
currentPos = 1;
panel.repaint();
}
private void rollDice() {
int step = random.nextInt(6)+1;
currentPos += step;
if(currentPos > 4) {
currentPos = 4-(currentPos-4);
}
panel.repaint();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == startBtn) {
startGame();
}
else if(e.getSource() == rollBtn) {
rollDice();
}
}
public static void main(String[] args) {
new FlyChess();
}
}
```
这个小游戏界面简单,分为两个按钮和一个棋盘,玩家点击“开始游戏”按钮后可以开始游戏,点击“掷骰子”按钮可以掷骰子前进,游戏规则与常规的飞行棋相同。需要注意的是,该示例代码只是一个简单的演示,如果您想要完整的飞行棋游戏,需要根据您的需求进行修改和扩展。
希望这个
阅读全文