2016年3月13日日曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • JavaScript (プログラミング言語)
  • Node.js(V8) (JavaScript engine)

Javascript for Kids (Nick Morgan 著、Angus Croll 寄稿、Miran Lipovaca イラスト、No Starch Press)のPart 1(Fundamentals)、Chapter 7(Creating a Hangman Game)、PROGRAMMING CHALLENGES #1: MORE WORDS、#2: CAPITAL LETTERS、#3: LIMITING GUESSES、#4: FIXING A BUG(No. 2187)を取り組んでみる。

PROGRAMMING CHALLENGES

コード(Emacs)

/*jslint         node    : true, continue : true,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, sloppy  : true, vars     : false,
  white  : true
*/
var words = ['javascript',
             'monkey',
             'amazing',
             'pancake',
             'scheme',
             'c'
            ],
    words_len = words.length,
    word = words[Math.floor(Math.random() * words_len)],
    word_len = word.length,
    answer_array = [],
    i,
    remaining_letters = word_len,
    guess,
    count = 20;

for (i = 0; i < word_len; i += 1) {
    answer_array[i] = '_';
}

while (remaining_letters > 0 && count > 0) {
    alert(answer_array.join(' '));
    guess = prompt('Guess a letter, or click Cancel to stop playing.');
    if (guess === null || guess === '') {
        break;
    }
    if (guess.toLowerCase() !== guess) {
        alert('Please enter a lower letter.');
        guess = guess.toLowerCase();
    }
    if (guess.length !== 1) {
        alert('Please enter a single letter.');
    } else {
        for (i = 0; i < word_len; i += 1) {
            if (word[i] === guess) {
                if (answer_array[i] === '_') {
                    answer_array[i] = guess;
                    remaining_letters -= 1;
                } else {
                    alert('guessed already.');
                }
            }                
        }
    }
    count -= 1;
}
alert(answer_array.join(' '));
alert('Good job! the answer was ' + word);

入出力結果(Terminal)

$ jslint sample.js

sample.js is OK.
$

0 コメント:

コメントを投稿