1.要求
一个猜拳游戏:设计一个人Tom和电脑玩猜拳游戏,电脑每次会随机生成0,1,2;0表是石头,1表示剪刀,2表示布
最后显示猜拳记录
2.代码
import java.util.Random;
import java.util.Scanner;
public class Exercise14 {
public static void main(String[] args) {
//记录赢了几场
int countWin = 0 ;
//记录电脑猜的数
int comGss= 0 ;
//记录Tom猜的数
int tomGss = 0 ;
//记录是比赛结果
String isWin ;
String[] theResult = new String[3];
//二维数组 用来记录每回合的猜拳 三场一回合
int [][] theRound = new int[3][3];
int j = 0 ;
int [] allTomGss = new int[3] ;
TomAndComputer tomAndComputer = new TomAndComputer();
Scanner scanner = new Scanner(System.in);
for (int i = 0 ;i<theRound.length;i++ ){
//电脑进行猜拳
tomAndComputer.setComputerGss();
//记录电脑猜的拳
comGss = tomAndComputer.computerGss ;
theRound[i][j+2] = comGss;
//Tom进行猜拳,并进行记录
System.out.println("请输入要猜的拳 0,1,2");
tomAndComputer.setTomGss(scanner.nextInt());
tomGss = tomAndComputer.tomGss;
theRound[i][j+1] = tomGss;
//记录第几回合
theRound[i][0] = i+1 ;
//记录Tom猜的拳 ,其实没必要做这个
allTomGss[i] = tomGss;
//进行猜拳,并记录猜拳的结果
isWin = tomAndComputer.compare(tomGss,comGss);
//输出本场结果
System.out.println("=========================");
System.out.println("Round:"+ tomAndComputer.round +" tomGss: " +
tomAndComputer.tomGss + " computerGss: "+tomAndComputer.computerGss +" "+isWin);
System.out.println("=========================");
countWin = tomAndComputer.getCount(isWin);
//记录猜拳结果
theResult[i] = isWin ;
}
//本回合比赛结束 ,数据本回合比赛情况
System.out.println("赢了"+ countWin+"场");
System.out.println("第几场"+"\t" + "Tom猜的"+"\t"+"电脑猜的"+"\t");
for (int b = 0 ;b<theRound.length ; b++){
for (int a = 0 ;a<theRound[b].length;a++ ){
System.out.print(theRound[b][a]+ "\t"+"\t");
}
System.out.println(" "+theResult[b]);
System.out.println();
}
}
}
class TomAndComputer{
//第几次比较
int round = 1;
//Tom赢的次数
int count ;
//电脑猜拳数
int computerGss ;
public void setComputerGss(){
Random random = new Random();
this.computerGss = random.nextInt(3);
}
//Tom猜拳
int tomGss ;
public void setTomGss(int tomGss){
if (tomGss > 2 || tomGss < 0 ){
System.out.println("输入错误,猜拳应是 0 ,1,2这三个数");
//抛出异常
throw new IllegalArgumentException("数据异常");
}else {
this.tomGss = tomGss;
}
}
//进行比较
public String compare (int tomGss , int computerGss){
if (tomGss ==0 && computerGss == 1){
return "你赢了" ;
}else if (tomGss == 1 && computerGss == 2){
return "你赢了" ;
}else if (tomGss == 2 && computerGss ==0){
return "你赢了" ;
}else if (tomGss == computerGss){
return "平手";
}
else {
return "你输了" ;
}
}
//对猜拳结果进行比较,并记录是第几场猜拳
public int getCount(String s){
round ++ ;
if (s.equals("你赢了")){
count ++ ;
}
return count ;
}
}