用java實現了一個簡單的猜拳游戲,準備記錄下來,算作是總結和回顧吧。程序運行結果如下:

1.首先你需要編寫一個電腦的類,類中有一個記錄獲勝幾次的成員變量,和一個出拳的方法(用取隨機數字來表示電腦出拳),代碼如下:
1 class Computer { 2 int count; 3 4 public int showFist() { 5 Random obj = new Random(); 6 // 利用Random類的nextInt()方法生成0-2之間的數 7 int number = obj.nextInt(3) + 1; 8 switch (number) { 9 case 1:10 System.out.2.然后你需要一個和電腦玩耍的人,類中同樣也是一個記錄獲勝的成員變量和一個出拳的方法(取控制臺用戶輸入的數值作為你出拳),代碼如下:
1 class Person { 2 int count; 3 4 public int showFist() { 5 Scanner input = new Scanner(System.in); 6 System.out.println("請出拳:1.石頭 2.剪刀 3.布 0.退出"); 7 int number = input.nextInt(); 8 switch (number) { 9 case 1:10 System.out.println("我出:石頭");11 break;12 case 2:13 System.out.println("我出:剪刀");14 break;15 case 3:16 System.out.println("我出:布");17 break;18 case 0:19 break;20 }21 return number;22 }23 }3.最后就是玩游戲的主體類,類中三個成員變量,分別是電腦、人、記錄玩總次數,還有一個構造函數用來初始化電腦和人對象,一個判斷輸贏的方法,一個打印結果方法,代碼如下:
1 public class FingerGuessing { 2 Person per; 3 Computer com; 4 int count; 5 6 public FingerGuessing() { 7 per = new Person(); 8 com = new Computer(); 9 count = 0;10 }11 12 public void gameBegin() {13 System.out.println("==========猜拳小游戲==========");14 System.out.println("= 游戲規則:1.石頭 2.剪刀 3.布 0.退出 =");15 System.out.println("===========================");16 int perno;17 int comno;18 do {19 perno = per.showFist();20 if (perno == 0) {21 showResult();22 break;23 }24 comno = com.showFist();25 if ((perno == comno)) {26 System.out.println("平局/n");27 this.count++;28 } else if ((perno - comno == -1) || (perno - comno == 2)) {29 System.out.println("恭喜,你贏了!/n");30 per.count++;31 this.count++;32 } else {33 System.out.println("很遺憾,你輸了!/n");34 com.count++;35 this.count++;36 }37 38 } while (perno != 0);39 40 }41 public void showResult() {42 System.out.println("與電腦共較量<" + this.count + ">次;");43 System.out.println("玩家獲勝<" + per.count + ">次;");44 System.out.println("電腦獲勝<" + com.count + ">次;");45 System.out.println("平局<" + (this.count-per.count-com.count) + ">次;");46 }47 48 public static void main(String[] args) {49 FingerGuessing game = new FingerGuessing();50 game.gameBegin();51 }52 } 這樣猜拳小游戲就OK了,來,和我猜拳吧!
新聞熱點
疑難解答