raye0621
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- tags: 讀書會 --- # JS30 讀書會 Day 30 - Whack A Mole Game! ![](https://i.imgur.com/45c9kfD.png) ## 摘要 打地鼠! 最後一天要實作的是打地鼠的遊戲,打地鼠的內容如下: 有六個洞會隨機出現地鼠,對著地鼠點擊即可得一分,遊戲時間10秒鐘。 ## 想像需要甚麼功能 可以把要實現的效果拆分,可以比較了解每一個小功能要幹嘛 1. 地鼠隨機出現的時間 2. 地鼠從六個洞隨機出現的位置 3. 結合 1. 2. 做出地鼠隨機出現 4. 點到地鼠時,分數++ ![](https://i.imgur.com/z5QWtWP.jpg) ## 隨機時間 >地鼠出現的隨機時間 我們希望有個 function 可以接收兩個時間作為參數,並且回傳兩個參數之間的一個隨機數。 - `Math.random()` 隨機回傳 0~1 之間 (0 <= 回傳值 < 1),的一個隨機小數。 ```javascript function randomTime(min, max) { return Math.round(Math.random() * (max - min)) + min } ``` 或是 ```javascript function randomTime(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min } ``` 補充: 如果跳太快可以先看這個對於 `Math.random()` 的初階用法。 ```javascript // 求一個 0~指定數之間的隨機數 function randomNum(num) { return Math.floor(Math.random() * num ) } randomNum(10) // 回傳 0~9 的隨機數 ``` [[筆記][JavaScript]用Math.random()取得亂數的技巧 ](https://ithelp.ithome.com.tw/articles/10197904) [[筆記][JavaScript]用Math.random()取得某區間內的隨機亂數 ](https://ithelp.ithome.com.tw/articles/10197920) ## 隨機的地鼠洞洞 >隨機從六個洞其中一個洞出現 我們希望有個 function 可以接受綁定全部 hole 的 DOM 元素作為參數,並隨機回傳其中一的 holes 的元素。 並且不希望他會連續兩次從相同的地洞冒出,所以在外面新增一個變數 `lastHole` 用來記住上次是從哪個洞冒出,並做判斷式。 ```javascript lastHole = hole function randomHole(holes) { const idx = Math.floor(Math.random() * holes.length) const hole = holes[idx] // console.log(hole) // 不希望他會連續兩次從相同的洞洞迸出來 建立一個新變數存取最後的 hole if (hole === lastHole) { console.log('重複了!') return randomHole(holes) } lastHole = hole return hole } ``` ## 地鼠隨機冒出 >地鼠冒出機制:地鼠隨機從六個洞冒出,並停留隨機的時間 合併上面的兩個 function 即可做出 為了停止,在外面宣告一個新變數用來停止地鼠冒出,這邊先加判斷式,停止的功能由下一個函式實作。 ```javascript let timeUp = false function peep() { const peepTime = randomTime(200, 1000) const peepHole = randomHole(holes) // console.log(peepTime, peepHole) peepHole.classList.add('up') // 這樣地鼠冒出的機制就完成了,接下來要讓它消失 setTimeout(() => { // 加上這行,讓他會縮回去 peepHole.classList.remove('up') //再加上 peep(),隨機出現的地鼠就完成囉! if(!timeUp) peep() }, peepTime) } ``` ## 遊戲開始 >遊戲開始:在一定時間內。地鼠隨機從六個洞冒出,並停留隨機的時間 將上面的函式加上停止的條件,並且設定遊戲開始的初始值,即可做出 - 用 `setTimeout` 設定一定時間後 timeUp 就會變成 true,這個用來判斷遊戲何時停止 - 初始值:記分板的分數、分數、設定停止的參數為 false ```javascript let timeUp = false function startGame() { scoreBoard.textContent = 0 timeUp = false score = 0 peep() setTimeout(() => timeUp = true, 10000) } ``` --- 這樣子就有得到一個遊戲開始的函式,只要執行他就會在時間內隨機的從地洞中跑出地鼠,接下來剩下點擊地鼠的計分事件囉~ 記得將開始的監聽掛上。 ```javascript document.querySelector('.start').addEventListener('click', startGame) ``` --- ## 點擊地鼠計分事件 >點擊到地鼠時分數++,記分板的分數同步 ```javascript // 將地鼠掛上監聽 moles.forEach(mole => mole.addEventListener('click', bonk)) ``` - `Event.isTrusted` 若事件物件是由使用者操作而產生,則 isTrusted 值為 true。簡單的防作弊機制。 [MDN Event.isTrusted ](https://developer.mozilla.org/zh-TW/docs/Web/API/Event/isTrusted) ```javascript function bonk(e) { // console.log(e) if(!e.isTrusted) return // 作弊仔 score++ // 點到之後馬上把 up 拿掉 this.parentNode.classList.remove('up') scoreBoard.textContent = score } ``` 最後只要點擊 start ,就可以開始玩啦~ [不知道甚麼時候會死的連結](http://rayes.tw/JS30/index-START.html) ## 謝謝大家,JS30 我要成為 JavaScript 大師 讀書會 平安落幕。 感謝 benben 的發起(?,還有大家的邀請 相信大家都有像當初的目標一樣,向 JS 大師邁進了一步! 第一個讀書會結束了,希望這個社群的第二個、第三個讀書會能繼續持續下去 我們下個讀書會見。 ![](https://i.imgur.com/Znl3xZb.png)

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully