石頭剪刀布--枚舉-隊列循環

 1 package randomzxw;
 2 
 3 import java.util.Scanner;
 4 
 5 enum EnumGuess {
 6     //定義剪刀,石頭,布。三個元素;
 7     剪刀("剪刀",1),石頭("石頭",2),布("布",3);
 8     private String name;
 9     private int index;
10     //構造函數
11     private EnumGuess(String name,int index){
12         this.name=name;
13         this.index=index;
14     }
15     //獲取索引
16     public int getIndex(){
17         return this.index;
18     }
19     //經過索引,用於提取用戶、電腦輸出的值;
20     public String getName(int index){
21         for(EnumGuess e:EnumGuess.values()){
22             if(e.getIndex()==index){
23                 return e.name;
24             }
25         }
26         return null;
27     }
28 }
29 public class guess1 {
30     public static void main(String[] args){
31         Scanner sc=new Scanner(System.in);
32         System.out.println("請出拳\t1-剪刀    2-石頭  3-布");
33         //用戶輸入
34         int cs1=sc.nextInt();
35         //電腦隨機值
36         int cs2=(int)(Math.random()*10)%3+1;
37         //將,剪刀石頭布當作是一個循環隊列,1->2->3 => 1=4-3 => 2=5-3 => 3=6-3;
38         //用戶值:1;電腦一、二、3,則temp=cs1-cs2的值爲1-1=0:平局;1-2=-1:輸;1-3=4-3=1:贏;
39         //用戶值:2;電腦一、二、3,則temp=cs1-cs2的值爲2-2=0:平局;2-3=-1:輸;2-1=1:贏;
40         //用戶值:3;電腦一、二、3,則temp=cs1-cs2的值爲3-3=0:平局;3-1=3-4=-1:輸;3-2=1:贏;
41         if(cs1-cs2==2){
42             cs2+=3;
43         }else if(cs1-cs2==-2){
44             cs1+=3;
45         }
46         int temp=cs1-cs2;
47         EnumGuess guess = EnumGuess.剪刀;
48         switch(temp){
49         case 1:
50             System.out.println("你出的是  " + guess.getName(cs1>3?cs1-3:cs1) + " \n電腦出的是  " + guess.getName(cs2>3?cs2-3:cs2) + "\n你贏啦");
51             break;
52         case 0:
53             System.out.println("你出的是  " + guess.getName(cs1>3?cs1-3:cs1) + " \n電腦出的是  " + guess.getName(cs2>3?cs2-3:cs2) + "\n平局啦");
54             break;
55         case -1:
56             System.out.println("你出的是  " + guess.getName(cs1>3?cs1-3:cs1) + " \n電腦出的是  " + guess.getName(cs2>3?cs2-3:cs2) + "\n你輸啦");
57             break;
58         }
59     }
60 }
相關文章
相關標籤/搜索