2016年4月30日土曜日

開発環境

Javascript for Kids (Nick Morgan 著、Angus Croll 寄稿、Miran Lipovaca イラスト、No Starch Press)のPart 2(Advanced JavaScript)、Chapter 10(Interactive Programming)、PROGRAMMING CHALLENGES #4: (MAKE A "CLICK THE HEADER" GAME!)、(No. 2714)を取り組んでみる。

PROGRAMMING CHALLENGES #4: (MAKE A "CLICK THE HEADER" GAME!)

コード(Emacs)

<!doctype html>
<html>
  <head>
  </head>
  <body>
    <div style="width:250px; height:250px;">
      <h1 id="heading">Hello world!</h1>
    </div>
    <script src="jquery.js"></script>
    <script src="sample4.js"></script>    
  </body>
</html>
/*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
*/
/*global $ */
var $heading = $('#heading'),
    timer,
    offset_left,
    offset_right,
    offset_top,
    offset_bottom,
    cur_left,
    cur_top,
    direction = 'right',
    pixels = 5,
    t = 20,
    counter = 0,
    fn;

offset_left = $heading.offset().left;
offset_right = offset_left + 200;
offset_top = $heading.offset().top;
offset_bottom = offset_top + 200;
cur_left = offset_left;
cur_top = offset_top;

fn = function () {
    if (direction === 'right') {
        cur_left += pixels;
        $heading.offset({left: cur_left});
        if (cur_left === offset_right) {
            direction = 'bottom';
        }
    } else if (direction === 'bottom') {
        cur_top += pixels;
        $heading.offset({top: cur_top});
        if (cur_top === offset_bottom) {
            direction = 'left';
        }
    } else if (direction === 'left') {
        cur_left -= pixels;
        $heading.offset({left: cur_left});
        if (cur_left === offset_left) {
            direction = 'top';
        }
    } else if (direction === 'top') {
        cur_top -= pixels;
        $heading.offset({top: cur_top});
        if (cur_top === offset_top) {
            direction = 'right';
        }
    }
};

timer = setInterval(fn, t);

$heading.click(function () {
    counter += 1;
    if (counter === 10) {
        clearInterval(timer);
        $heading.replaceWith('<h1>Your Win.</h1>');        
    } else {
        clearInterval(timer);
        $heading.text('Hello world! ' + counter);
        t /= 2;
        timer = setInterval(fn, t);
    }
});

Hello world!

0 コメント:

コメントを投稿