1. 程式人生 > >java 石頭剪子布遊戲

java 石頭剪子布遊戲

oid 代碼 reader col tin rgs iss false bool

源代碼 StoneGame.java

 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStreamReader;
 4 import java.util.Random;
 5 
 6 public class StoneGame {
 7     private static int playerScores = 0;
 8     private static int computerScores = 0;
 9     private static boolean playing = true
; 10 private static String[] playerSkills = {"石頭", "剪子", "布"}; 11 12 public static void main(String[] args) { 13 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); 14 try { 15 System.out.println("輸入:石頭[1] 剪子[2] 布[3] 退出[4]"); 16 while
(playing) { 17 int playerSkill = Integer.parseInt(bufferedReader.readLine()); 18 Random random = new Random(); 19 int computerSkill = random.nextInt(3) + 1; 20 if (playerSkill == 4) { 21 System.out.println("Bye."); 22
playing = false; 23 break; 24 } 25 if (playerSkill > 0 && playerSkill < 4) { 26 System.out.println("玩家: " + playerSkills[playerSkill - 1]); 27 System.out.println("電腦: " + playerSkills[computerSkill - 1]); 28 compare(playerSkill, computerSkill); 29 System.out.println("玩家分數: " + playerScores + " " + "電腦分數: " + computerScores); 30 } else { 31 System.out.println("請重試."); 32 } 33 } 34 } catch (IOException e) { 35 e.printStackTrace(); 36 } catch (NumberFormatException e) { 37 System.out.println("請輸入正確的數字!"); 38 } 39 } 40 41 private static void compare(int playerSkill, int computerSkill) { 42 if (playerSkill == computerSkill) { 43 System.out.println("平局."); 44 return; 45 } 46 if (playerSkill == 1) { // player skill is stone. 47 if (computerSkill == 2) { 48 System.out.println("玩家勝利."); 49 playerScores++; 50 } else { 51 System.out.println("電腦勝利."); 52 computerScores++; 53 } 54 } 55 if (playerSkill == 2) { // player skill is scissor. 56 if (computerSkill == 3) { 57 System.out.println("玩家勝利."); 58 playerScores++; 59 } else { 60 System.out.println("電腦勝利."); 61 computerScores++; 62 } 63 } 64 65 if (playerSkill == 3) { // player skill is cloth. 66 if (computerSkill == 1) { 67 System.out.println("玩家勝利."); 68 playerScores++; 69 } else { 70 System.out.println("電腦勝利."); 71 computerScores++; 72 } 73 } 74 } 75 }

java 石頭剪子布遊戲