人机博弈小游戏
实现功能
电脑随机出拳
玩家任意出拳
五局三胜制
可判断最终赢家
下面展示 代码。
// A code block
var foo = 'bar';
// An highlighted block
package day0423;
import java.util.Random;
import java.util.Scanner;
public class Test02 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Test02 fg = new Test02();
fg.showMenu();
}
//功能菜单
public void showMenu(){
System.out.println("***欢迎进行猜拳小游戏***");
System.out.println("游戏开始");
Scanner key = new Scanner(System.in);
System.out.println("请选择你的游戏对手(1.秦 2.婷 3.婷婷):");
int num = key.nextInt();
System.out.println("请输入玩家的姓名:");
String name = key.next();
String enemyName = "";
switch (num) {
case 1:
enemyName = "秦";
break;
case 2:
enemyName = "婷";
break;
case 3:
enemyName = "婷婷";
break;
}
System.out.println(name+"VS"+enemyName+"对战");
System.out.println("确定开始吗?(按y开始,按其他键结束)");
String temp = key.next();
if(temp.equalsIgnoreCase("y")){
play();
}else{
System.out.println("退出游戏,系统结束");
}
}
public void play(){
Scanner key = new Scanner(System.in);
int count1=0;
int count2=0;
for(int i=0;i<5;i++){
System.out.println("***第"+(i+1)+"把***");
System.out.println("请出(1.石头2.剪刀3.布)");
int temp1=key.nextInt();
String myChoose = change(temp1);
Random rd = new Random();
int temp2 = rd.nextInt(3)+1;
String dChoose = change(temp2);
System.out.println("你出拳:"+myChoose);
System.out.println("系统出拳:"+dChoose);
if(temp1==temp2 ){
System.out.println("平!");
}else if(temp1==1&&temp2==3||temp1==2&&temp2==1||temp1==3&&temp2==2){
System.out.println("敌人赢了!");
count2++;
}else{
System.out.println("玩家赢了!");
count1++;
}
}
if(count1>count2){
System.out.println("最终结果你赢了!");
}
else
if(count1==count2){
System.out.println("最终结果平局");
}
else
if(count1
System.out.println("最终结果你输了!");
}
}
public String change(int Choose){
String str = "";
switch (Choose) {
case 1:
str = "石头";
break;
case 2:
str = "剪刀";
break;
case 3:
str = "布";
break;
}
return str;
}
}
下面是运行结果
标签:key,Java,Scanner,System,小游戏,人机,println,enemyName,out
来源: https://blog.csdn.net/weixin_46554776/article/details/105836201