自己初学,做的一个小玩意(姓名作战),希望大家多指教
import java.awt.*;import java.awt.event.*;
import javax.swing.*;
import java.math.*;
public class ASC2 extends JFrame implements ActionListener {
private JPanel jp = new JPanel();
private JButton jb = new JButton("开战");
private JTextArea jt1 = new JTextArea();
private JTextArea jt2 = new JTextArea();
private JTextArea jt = new JTextArea();
private String[] wg = new String[] { "乾坤大挪移", "葵花宝典", "金刚不坏神功" };
public ASC2() {
// TODO Auto-generated constructor stub
jp.setLayout(null); // 面板设置为自由布局,而不是THIS(窗体)
jt1.setBounds(5, 5, 180, 20);
jt2.setBounds(295, 5, 180, 20);
jb.setBounds(205, 5, 70, 20);
jt.setBounds(5, 110, 470, 120);
jb.addActionListener(this);
jt1.setLineWrap(true);
jt1.setEditable(true);
jt2.setLineWrap(true);
jt2.setEditable(true);
jp.add(jt1);
jp.add(jt2);
jp.add(jb);
jp.add(jt);
this.add(jp);
this.setTitle("姓名大作战");
this.setBounds(110, 110, 500, 300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
int sum1 = 0, sum2 = 0;
char[] ch1 = jt1.getText().toCharArray();
char[] ch2 = jt2.getText().toCharArray();
for (int i = 0; i < ch1.length; i++) {
sum1 = sum1 + (int) (ch1[i]);
}
for (int i = 0; i < ch2.length; i++) {
sum2 = sum2 + (int) (ch2[i]);
}
if (e.getSource() == jb) {
int[] k1 = new int[3], k2 = new int[3];
for (int i = 0; i < 3; i++) {
if (i < 2) {
k1[i] = (int) (Math.random() * sum1);
k2[i] = (int) (Math.random() * sum2);
} else {
k1[i] = sum1 - k1[0] - k1[1];
k2[i] = sum2 - k2[0] - k2[1];
}
if ((int) (Math.random() * 4) % 2 == 0) {
jt.append(jt1.getText().toString()
+ "使用了"
+ wg[(int) (Math.random() * (wg.length - 1))]
.toString() + "打了"
+ jt2.getText().toString()
+ Math.abs(k1[i] - k2[i]) + "滴血\n");
} else {
jt.append(jt2.getText().toString()
+ "使用了"
+ wg[(int) (Math.random() * (wg.length - 1))]
.toString() + "打了"
+ jt1.getText().toString()
+ Math.abs(k1[i] - k2[i]) + "滴血\n");
}
}
if (sum1 > sum2) {
jt.append(jt1.getText().toString() + "打败了"
+ jt2.getText().toString());
} else if (sum1 < sum2) {
jt.append(jt2.getText().toString() + "打败了"
+ jt1.getText().toString());
} else {
jt.append(jt1.getText().toString() + " "
+ jt2.getText().toString() + "两败俱伤,不分胜负");
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new ASC2();
}
}