2017年4月5日水曜日

開発環境

Head First JavaScript Programming (Eric T. Freeman (著)、Elisabeth Robson (著)、O'Reilly Media)の Chapter 2.(Going further - Writing Real Code)、How the while loop works の SHARPEN YOUR PENCIL(No. 1332) を取り組んでみる。

SHARPEN YOUR PENCIL(No. 1332)

コード(Emacs)

HTML5

<button id="run0">run</button><button id="clear0">clear</button>
<pre id="output0"></pre>

<script src="battleship2.js"></script>

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0');

let logAlert = (msg) => {
    pre0.textContent += msg + '\n';
    alert(msg);
};
let logPrompt = (msg) => {
    pre0.textContent += msg + '\n';
    return prompt(msg);
};

btn0.onclick = () => {
    let location1 = 3,
        location2 = 2,
        location3 = 5,
        guess,
        hits = 0,
        guesses = 0,
        isSunk = false;
    
    while (isSunk === false) {
        guess = logPrompt('Ready, aim, fire! (enter number from 0-6):');
        if (guess === 'q') {
            break;
        }
        guess = parseInt(guess, 10);
        if (guess < 0 || 6 < guess) {
            logAlert('please enter a valid cell number!');
        } else {
            if (guess === location1 || guess === location2 || guess === location3) {
                logAlert('HIT!');
                hits += 1;
                if (hits === 3) {
                    isSunk = true;
                    logAlert('You sank my battleship!');
                }            
            } else {
                logAlert('MISS');
            }
        }
    }
};

btn1.onclick = () => {
    pre0.textContent = '';
};




    







						

0 コメント:

コメントを投稿