Java中利用随机数的猜拳游戏

时间:2023-12-15 17:13:02

  Java中利用随机数的猜拳游戏,实现非常简单,重难点在于随机数的产生。

  首先GameJude类是用于判断输赢的一个类:

 package testGame;

 public class GameJudge {
private String marks1 = "拳头";
private String marks2 = "拳头";
private int personCout = 0;
private int computerCout = 0;
private int cout = 0;
public void juge(int person, int computer) {
switch (person) {
case 1:
marks1 = "石头";
break;
case 2:
marks1 = "剪刀";
break;
case 3:
marks1 = "布";
break;
case 4:
System.out.println("用户赢"+this.personCout+"次\n电脑赢"+this.computerCout+"次\n平局"+this.cout+"次");
return;
}
switch (computer) {
case 1:
marks2 = "石头";
break;
case 2:
marks2 = "剪刀";
break;
case 3:
marks2 = "布";
break;
} if (person == computer) {
System.out.println("用户出" + marks1 + "\n电脑出" + marks2 + "\n结果:平局!");
cout++;
} else if ((person == 1 && computer == 2)|| (person == 2 && computer == 3)|| (person == 3 && computer == 1)) {
System.out.println("用户出" + marks1 + "\n电脑出" + marks2 + "\n结果:用户赢!");
personCout++;
} else {
System.out.println("用户出" + marks1 + "\n电脑出" + marks2 + "\n结果:电脑赢!");
computerCout++;
}
}
// public void shouGameCout(){
// System.out.println("用户赢"+this.personCout+"次\n电脑赢"+this.computerCout+"次\n平局"+this.cout+"次");
// }
}

  接下TestGame类是一个启动类,显示输入输出,退出统计游戏结果:

 package testGame;

 import java.util.Scanner;
import java.util.Random;
public class TestGame { /**
* @param 显示输入输出,推出时统计游戏结果
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
Random r = new Random();
GameJudge g = new GameJudge();
int person = 0;
while (person != 4) {
System.out.println("------------------猜拳游戏------------------");
System.out.println("请出拳(1、石头;2、剪刀;3、布;4、退出)");
person = sc.nextInt();
if( person == 1 || person == 2 || person == 3 || person == 4){
int computer = r.nextInt(3)+1;
g.juge(person, computer);
}else{
System.out.println("输入有误,请重新输入");
continue;
}
}
}
}

这个游戏我曾经写过几次,后来做了一些小的改动以满足作业的要求,主要用的就是随机数的产生和if条件语句,哈哈^_^。

加油!!!