猜拳代码java java编写猜拳小游戏

Java使用循环,实现猜拳游戏统计多少局及胜率?为了让游戏有参与感 , 并体现java面对对象的思想,我先创建一个Player选手类,包含选手的名字playerName还有出拳方法guess() 。出拳时采用随机获取0、1和2的方式分别代表石头、剪刀和布,代码如下:
public class Player {
private String playerName;
public Player(String playerName) {
this.playerName = playerName;
}
public String getPlayerName() {
return playerName;
}
//出拳方法 0-石头 1-剪刀 2-布
public int guess() {
//随机获取0、1、2
int num = new Random().nextInt(3);
if (num == 0) {
System.out.print("选手" + this.playerName + "出的是石头 ");
} else if (num == 1) {
System.out.print("选手" + this.playerName + "出的是剪刀 ");
} else if (num == 2) {
System.out.print("选手" + this.playerName + "出的是布 ");
}
return num;
}
}
然后在主类中,首先要输入对局的总数,然后创建两名选手进行pk,在pk()方法中制定了获胜规则,详见代码注释 。最终统计并利用BigDecimal计算胜率(BigDecimal可以很完美的解决整数除法及其四舍五入保留小数的问题):
public class Main {
public static void main(String[] args) {
System.out.println("请输入本局局数:");
Scanner scanner = new Scanner(System.in);
int sum = scanner.nextInt();
//创建结果数组,resultArray[0]代表p1的获胜局数,resultArray[1]代表p2的获胜局数,resultArray[2]代表平局局数
int[] resultArray = new int[3];
//创建两名选手
Player p1 = new Player("张三");
Player p2 = new Player("李四");
for (int i = 0; isum; i++) {
//根据总局数进行pk
int result = pk(p1, p2);
if (result == 1) {
resultArray[0]++;
} else if (result == -1) {
resultArray[1]++;
} else {
resultArray[2]++;
}
}
System.out.println("");
System.out.println("最终结果统计:");
System.out.println("选手[" + p1.getPlayerName() + "]获胜局数为:" + resultArray[0] + ",胜率为:" +
new BigDecimal(resultArray[0]).multiply(new BigDecimal(100).divide(new BigDecimal(sum), 2, BigDecimal.ROUND_HALF_UP)) + "%");
System.out.println("选手[" + p2.getPlayerName() + "]获胜局数为:" + resultArray[1] + ",胜率为:" +
new BigDecimal(resultArray[1]).multiply(new BigDecimal(100).divide(new BigDecimal(sum), 2, BigDecimal.ROUND_HALF_UP)) + "%");
System.out.println("平局局数为:" + resultArray[2] + ",平局率为:" +
new BigDecimal(resultArray[2]).multiply(new BigDecimal(100).divide(new BigDecimal(sum), 2, BigDecimal.ROUND_HALF_UP)) + "%");
}
//0-石头 1-剪刀 2-布
//return 0:平局 1:p1获胜 -1:p2获胜
private static int pk(Player p1, Player p2) {
System.out.println("--------------------");
int a = p1.guess();
int b = p2.guess();
System.out.print("\n对局结果:");
//出拳相同平局
if (a == b) {
System.out.println("平局");
return 0;
}
//p1获胜条件:p1出石头时p2出剪刀 , p1出剪刀时p2出步,p1出布时p2出石头
else if ((a == 0b == 1) || (a == 1b == 2) || (a == 2b == 0)) {
System.out.println("选手[" + p1.getPlayerName() + "]获胜");
return 1;
}
//p2获胜条件:p1出石头时p2出布 , p1出剪刀时p2出石头,p1出布时p2出剪刀
else if ((a == 0b == 2) || (a == 1b == 0) || (a == 2b == 1)) {
System.out.println("选手[" + p2.getPlayerName() + "]获胜");
return -1;
} else {
//因为规定了随机数产生0、1、2,所以其实不会走到本分支
throw new IllegalArgumentException("本局无效");
}
}
}
对局5局的运行结果:

推荐阅读