猜拳游戏三局两胜------java实现代码

package com.javasm.exerices02;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner; /**
*
*TODO 石头剪刀布猜拳游戏,三局两胜
* @author caolei 2018年5月2日下午10:51:23
* RockPaperScissors
*/
public class RockPaperScissors {
// 用于存放猜拳结果
private static List<String> gameResult; public static void crGuessingGame(Scanner sc) {
gameResult = new ArrayList<String>();
// 存储结果集
char[] finger = { '锤', '剪', '包' };
// 用于接收每一次的猜拳结果
String result;
// 用于计算机猜拳
Random random = new Random();
// 记录计算机获胜次数
int computerWinNumber = 0;
// 计算玩家获胜次数
int playerWinNumber = 0;
// 记录猜拳第几轮
int i = 0;
// 循环出拳
while (true) {
System.out.println("第" + (i + 1) + "轮,请出拳:");
// 计算机生成的随机数
int computerGet = random.nextInt(3);
// 用户输入的数
int playerInput = sc.nextInt();
// 记录猜拳结果
result = finger[computerGet] + "," + finger[playerInput];
// 将结果放入集合中
gameResult.add(result); /*
* 第一种通过if判断结果
*
* if (computerGet == 0 && playerInput != 0) {
* if (playerInput == 1)
* computerWinNumber++;
* playerWinNumber++;
*
* } else if (computerGet == 1 && playerInput != 1) {
* if (playerInput == 2)
* computerWinNumber++;
* playerWinNumber++;
* } else if (computerGet == 2 && playerInput != 2) {
* if (playerInput == 0)
* computerWinNumber++;
* playerWinNumber++;
* }
*/
/**
* 第二种通过switch判断结果
*/
switch (computerGet) {
case 0:
if (playerInput == 1)
computerWinNumber++;
if (playerInput == 2)
playerWinNumber++;
break; case 1:
if (playerInput == 2)
computerWinNumber++;
if (playerInput == 0)
playerWinNumber++; break;
case 2:
if (playerInput == 0)
computerWinNumber++;
if (playerInput == 1)
playerWinNumber++;
break; default:
break;
}
// 记录游戏轮数
i++;
// 判断是否有人取得胜利
if (computerWinNumber == 2 || playerWinNumber == 2) {
break;
} }
// 判断获胜者
if (computerWinNumber > playerWinNumber) {
System.out.println("电脑获胜!");
} else {
System.out.println("恭喜你获胜!");
}
// 输出猜拳结果
System.out.println("具体结果如下:");
System.out.println("电脑,你");
for (String results : gameResult) {
System.out.println("{ " + results + " }");
} }
}

  

上一篇:SQL利用Case When Then多条件判断


下一篇:linux安装python