iT邦幫忙

2021 iThome 鐵人賽

DAY 14
0
自我挑戰組

JAVA的實作與應用系列 第 14

Day14 Number Guessing

今天要利用之前學到的東西寫一個猜數字遊戲,此猜數字遊戲要符合以下條件:
1 猜數字範圍介於0-99間,且包含0跟99,故程式在開始的時候必須要隨機生成一個0-99間數字。
2 若玩家輸入的數字等於程式生成的數字的話,顯示Bingo,代表玩家贏得了遊戲。
3 若玩家輸入數的數字超出了範圍,則顯示Out of range, Try again,要求玩家重新輸入數字,若輸入的範圍還是超過則以此類推,若輸入在範圍內得重新進入比較。
4 若範圍已經縮小到 大值 – 小值 小於等於2,也就是玩家剩兩個數字可以猜時,如果玩家猜錯,則遊戲結束,玩家輸掉遊戲,顯示Game Over。

程式實作如下:
Step 1 因為設定的範圍是0-99間,因此宣告最大值max = 99、最小值min = 0
為整數int。
https://ithelp.ithome.com.tw/upload/images/20210926/20140456lS2AbNmHZP.png

Step 2 要取得使用者輸入的數,使用scanner方法。
https://ithelp.ithome.com.tw/upload/images/20210926/20140456mJskRtpitT.png

Step 3 宣告number為int,並由電腦產生這個number,使用random方法。
https://ithelp.ithome.com.tw/upload/images/20210926/20140456qr1SMGUX1A.png

Step 4 接著進入while迴圈,條件設為true,代表只要程式執行就會進入迴圈。
https://ithelp.ithome.com.tw/upload/images/20210926/20140456tLX9aOuYkv.png

Step5 第一個if條件式,在每次迴圈執行時,都先檢查一次 大值 – 小值 是否有小於等於2,若符合此條件則則進入此迴圈,代表玩家輸了遊戲,顯示Game Over,並將scanner close掉,不再請使用者輸入數值,且break跳出迴圈,結束程式執行。
https://ithelp.ithome.com.tw/upload/images/20210926/2014045651028EvdYB.png

執行結果如下
https://ithelp.ithome.com.tw/upload/images/20210926/2014045615wJCp2epN.png

Step 6 若不符合第一個if條件式,則印出Please input a number,並取得使用者輸入的數字input,並宣告其為int。
https://ithelp.ithome.com.tw/upload/images/20210926/20140456kphs9xaH18.png

執行結果如下
https://ithelp.ithome.com.tw/upload/images/20210926/20140456NUoXTlTWKI.png

Step 7 測試使用者輸入的數是否有在範圍內。用if else迴圈,若input > 99
或0 > input,顯示Out of range, Try again,並請使用者再次輸入。
https://ithelp.ithome.com.tw/upload/images/20210926/20140456X1xufEudSZ.png

執行結果如下
https://ithelp.ithome.com.tw/upload/images/20210926/20140456EFhsEEEhGY.png

Step 8 測試輸入的數(input)比隨機產生的數(number)大還是小,
若比較大,印出(min : input – 1)也就是使用者接下來要猜的範圍,
反之比較小的話,印出(input + 1 : max),max 跟 min 的值,在迴圈裡是會一直變的,輸入的值比較大的話則max = input – 1,反之min = input + 1。
https://ithelp.ithome.com.tw/upload/images/20210926/20140456DV3B6DVaIu.png

執行結果如下
https://ithelp.ithome.com.tw/upload/images/20210926/201404565ifzb1MzpV.png

Step 9 若使用者輸入的數=電腦產生的數,顯示Bingo,玩家贏的遊戲,跳出迴圈結束程式。
https://ithelp.ithome.com.tw/upload/images/20210926/201404564nLp4V9kbP.png
https://ithelp.ithome.com.tw/upload/images/20210926/20140456tOqA2UxwVY.png

程式全碼如下
https://ithelp.ithome.com.tw/upload/images/20210926/201404560On3Xsqjq5.png


上一篇
Day13 For迴圈
下一篇
Day 15 Array
系列文
JAVA的實作與應用30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言