用Java编译制作猜拳小游戏,利用Eclipse制作的一个简单UI猜拳小游戏
时间: 2023-11-12 14:04:22 浏览: 216
好的,以下是使用Java编写的猜拳小游戏示例代码,使用Eclipse进行开发和调试:
```java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class RockPaperScissorsGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private static final String[] OPTIONS = {"石头", "剪刀", "布"};
private JLabel lblResult;
private JButton[] btnOptions;
public RockPaperScissorsGame() {
setTitle("猜拳小游戏");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
initComponents();
setVisible(true);
}
private void initComponents() {
lblResult = new JLabel();
lblResult.setPreferredSize(new Dimension(WIDTH, 50));
lblResult.setHorizontalAlignment(JLabel.CENTER);
lblResult.setFont(new Font("Arial", Font.BOLD, 24));
JPanel pnlOptions = new JPanel(new GridLayout(1, 3, 10, 0));
btnOptions = new JButton[3];
for (int i = 0; i < 3; i++) {
JButton btnOption = new JButton(OPTIONS[i]);
btnOption.setPreferredSize(new Dimension((WIDTH - 40) / 3, 150));
btnOption.setFont(new Font("Arial", Font.BOLD, 18));
btnOption.setForeground(Color.WHITE);
btnOption.setBackground(Color.GRAY);
btnOption.addActionListener(this);
pnlOptions.add(btnOption);
btnOptions[i] = btnOption;
}
JPanel pnlMain = new JPanel(new BorderLayout());
pnlMain.add(lblResult, BorderLayout.NORTH);
pnlMain.add(pnlOptions, BorderLayout.CENTER);
add(pnlMain);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
JButton btnOption = (JButton) e.getSource();
int userValue = -1;
for (int i = 0; i < 3; i++) {
if (btnOption == btnOptions[i]) {
userValue = i + 1;
break;
}
}
int computerValue = new Random().nextInt(3) + 1;
int resultValue = (userValue - computerValue + 3) % 3;
String resultMsg = String.format("你选择了%s,计算机选择了%s,%s", OPTIONS[userValue - 1], OPTIONS[computerValue - 1], getResultText(resultValue));
lblResult.setText(resultMsg);
}
}
private String getResultText(int resultValue) {
switch (resultValue) {
case 0:
return "平局";
case 1:
return "你赢了";
case 2:
return "你输了";
default:
return "";
}
}
public static void main(String[] args) {
new RockPaperScissorsGame();
}
}
```
这是一个使用Java Swing库编写的简单UI猜拳小游戏,包含一个标题、三个选项和一个结果显示区域。每个选项都是一个按钮,点击任意一个按钮时,程序会生成计算机随机选择的选项值,并计算出猜拳结果,最后在结果显示区域显示结果。
阅读全文