java代码实现人机猜拳 java猜拳代码简单

猜拳游戏java能输出游戏时间Java实现猜拳游戏的核心在于电脑随机数的生成,Java中的随机数生成方法是java代码实现人机猜拳:
首先引入包import java.util.*;然后int r=new Random().nextInt(3);(nextInt中的数字三代表随机数生成的个数,从零开始)
所以在猜拳的输入中需要有0、1、2三个数字代替,如果要输入汉字 , 则用if进行相应判断即可 。
在实现的游戏中实现①猜拳java代码实现人机猜拳;②记录胜负;③玩家决定游戏局数;④输出获胜、失败及平局;⑤统计总共的胜负结果(根据获胜次数判断)
①猜拳基础功能:该部分代码可以放到一个方法中,减少主函数代码量 。
电脑出拳即int r=new Random().nextInt(3);注意:该部分一定要写在for循环内部,否则无法实现每次不同的随机数 。
通过if判断双方出拳是否相等if(a==0r==0)else if(a==0r==1)else if(a==0r==2)即可实现猜拳,if内直接输出相关语句即可
②记录胜负:定义猜拳方法为int,通过返回值记录相关比赛的胜负情况,可以用0--失败;1--获胜;2--平局 进行记录 , 在主函数中对相应抛出的数字记录即可
if(a==0r==0){
System.out.println("The computer comes out with cloth,it was a draw. ");
return 2;
}
h=comp.compare(a,r);if (h==1)j++;
登录后复制
③玩家决定局数: 定义一个数 , 在循环中不大于该数即可
④输出获胜、失败及平局: j、k即胜利和失败,平局数即n-j-k 。
⑤统计结果,直接用if比较i、j的数字结果即可 。
主函数部分:
package SS2_5;
import java.util.*;
public class Main {
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
Compare comp=new Compare();
int h=0,j=0,k=0;
System.out.println("rules:0--cloth;1--stone;2--scissors.\nU can choose how many times you want to play:");
int n=scanner.nextInt();
for(int i=1;i=n;i++){
System.out.print("It's the "+i+" round,your turn:");
int a=scanner.nextInt();
int r=new Random().nextInt(3);
switch (a){
case 0:
h=comp.compare(a,r);
break;
case 1:
h=comp.compare(a,r);
break;
case 2:
h=comp.compare(a,r);
break;
default:
System.out.println("Wrong number!");
break;
}
if (h==1)
j++;
else if(h==0)
k++;
}
System.out.println("The total times you won are "+j+",The draw times are "+(n-j-k)+".");
if(jk)
System.out.println("You are the final winner");
else if(kj)
System.out.println("The computer is the winner.");
if(j==k)
System.out.println("The final result is draw");
}
}
登录后复制
compare方法部分
package SS2_5;
public class Compare {
public int compare(int a,int r){
int counter=0;
if(a==0r==0){
System.out.println("The computer comes out with cloth,it was a draw. ");
return 2;
}
else if(a==0r==1){
System.out.println("The computer comes out with stone, you won. ");
return 1;
}
else if(a==0r==2){
System.out.println("The computer comes out with scissor,you lost. ");
return 0;
}
else if(a==1r==0){
System.out.println("The computer comes out with cloth,you lost. ");
return 0;
}
else if(a==1r==1){
System.out.println("The computer comes out with stone,it was a draw. ");
return 2;
}
else if(a==1r==2){
System.out.println("The computer comes out with scissors,you won. ");
return 1;
}
else if(a==2r==0){
System.out.println("The computer comes out with cloth,you won. ");
return 1;
}
else if(a==2r==1){
System.out.println("The computer comes out with stone,you lost. ");

推荐阅读