Java中利用随机数的猜拳游戏,实现非常简单,重难点在于随机数的产生。
首先GameJude类是用于判断输赢的一个类:
1 package testGame; 2 3 public class GameJudge { 4 private String marks1 = "拳头"; 5 private String marks2 = "拳头"; 6 private int personCout = 0; 7 private int computerCout = 0; 8 private int cout = 0; 9 public void juge(int person, int computer) { 10 switch (person) { 11 case 1: 12 marks1 = "石头"; 13 break; 14 case 2: 15 marks1 = "剪刀"; 16 break; 17 case 3: 18 marks1 = "布"; 19 break; 20 case 4: 21 System.out.println("用户赢"+this.personCout+"次 电脑赢"+this.computerCout+"次 平局"+this.cout+"次"); 22 return; 23 } 24 switch (computer) { 25 case 1: 26 marks2 = "石头"; 27 break; 28 case 2: 29 marks2 = "剪刀"; 30 break; 31 case 3: 32 marks2 = "布"; 33 break; 34 } 35 36 if (person == computer) { 37 System.out.println("用户出" + marks1 + " 电脑出" + marks2 + " 结果:平局!"); 38 cout++; 39 } else if ((person == 1 && computer == 2)|| (person == 2 && computer == 3)|| (person == 3 && computer == 1)) { 40 System.out.println("用户出" + marks1 + " 电脑出" + marks2 + " 结果:用户赢!"); 41 personCout++; 42 } else { 43 System.out.println("用户出" + marks1 + " 电脑出" + marks2 + " 结果:电脑赢!"); 44 computerCout++; 45 } 46 } 47 // public void shouGameCout(){ 48 // System.out.println("用户赢"+this.personCout+"次 电脑赢"+this.computerCout+"次 平局"+this.cout+"次"); 49 // } 50 }
接下TestGame类是一个启动类,显示输入输出,退出统计游戏结果:
1 package testGame; 2 3 import java.util.Scanner; 4 import java.util.Random; 5 public class TestGame { 6 7 /** 8 * @param 显示输入输出,推出时统计游戏结果 9 */ 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 Scanner sc = new Scanner(System.in); 13 Random r = new Random(); 14 GameJudge g = new GameJudge(); 15 int person = 0; 16 while (person != 4) { 17 System.out.println("------------------猜拳游戏------------------"); 18 System.out.println("请出拳(1、石头;2、剪刀;3、布;4、退出)"); 19 person = sc.nextInt(); 20 if( person == 1 || person == 2 || person == 3 || person == 4){ 21 int computer = r.nextInt(3)+1; 22 g.juge(person, computer); 23 }else{ 24 System.out.println("输入有误,请重新输入"); 25 continue; 26 } 27 } 28 } 29 }
这个游戏我曾经写过几次,后来做了一些小的改动以满足作业的要求,主要用的就是随机数的产生和if条件语句,哈哈^_^。
加油!!!