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;
}
}
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于