接(二)
使用者類,電腦人類,我們已經編寫完了··剩下的就是遊戲類了,說白了,遊戲類的主要作用就是控制遊戲的流程,就相當於遊戲機的手柄。
不多說了,看代碼吧
Code:
- import java.util.Scanner;
-
- public class Game
- {
- Person per;
- Computer com;
- int count;
- Scanner input = new Scanner(System.in);
-
- //構造方法,初始化
- public Game()
- {
- per = new Person();
- com = new Computer();
- count = 0;
- }
-
- //開始遊戲
- public void gameBegin()
- {
- System.out.println("==========猜拳小遊戲==========");
- System.out.println("==============================");
- System.out.println("遊戲規則:1.拳頭 2.剪刀 3.包袱");
- System.out.println("請選擇人物:1.小強 2.小毛 3.小明");
- int number = input.nextInt();
-
- switch(number)
- {
- case 1:
- per.name = "小強";
- System.out.println("您選擇的是小強");
- break;
- case 2:
- per.name = "小毛";
- System.out.println("您選擇的是小毛");
- break;
- case 3:
- per.name = "小明";
- System.out.println("您選擇的是小明");
- break;
- }
-
- //記錄出的拳
- int perno;
- int comno;
-
- System.out.println("要開始遊戲嗎?(y/n)");
- String answer = input.next();
-
- while(answer.equalsIgnoreCase("y"))
- {
- perno = per.showFist();
- comno = com.showFist();
-
- //判斷結果
- if((perno==1&&comno==1)||(perno==2&&comno==2)||(perno==3&&comno==3))
- {
- System.out.println("平局");
- //記錄較量總次數
- this.count ++;
- }
- else if((perno==1&&comno==2)||(perno==2&&comno==3)||(perno==3&&comno==1))
- {
- System.out.println("玩家勝");
- per.count ++;
- this.count++;
- }
- else
- {
- System.out.println("電腦勝");
- com.count++;
- this.count++;
- }
-
- System.out.println("是否要繼續?(y/n)");
- answer = input.next();
- }
-
- //當結束時,顯示總結果
- showResult();
- }
-
- //顯示結果
- public void showResult()
- {
- System.out.println("較量總次數:" + this.count);
- System.out.println("玩家勝次數:" + per.count);
- System.out.println("電腦勝次數:" + com.count);
- }
- }
接下來,編寫測試類別
Code:
- public class Test
- {
- public static void main(String args [])
- {
- Game game = new Game();
-
- game.gameBegin();
- }
- }
運行一下,看看吧··
到現在,這個簡單的JAVA猜拳小遊戲就完成了··