2016年8月17日水曜日

開発環境

Javascript for Kids (Nick Morgan 著、Angus Croll 寄稿、Miran Lipovaca イラスト、No Starch Press)のPart 3(Canvas)、Chapter 16(Making a Snake Game: Part 1)、PROGRAMMING CHALLENGES、#1, #2:PUTTING IT TOGETHER, ANIMATING THE SCORE(4581)を取り組んでみる。

PROGRAMMING CHALLENGES、#1, #2:PUTTING IT TOGETHER, ANIMATING THE SCORE(4581)

コード(Emacs)

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Snake!</title>
  </head>
  <body>
    <canvas id="canvas0" width="400" height="400"></canvas>
    
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    
    <script src="sample1.js"></script>
  </body>
</html>
(function () {
    var canvas = document.querySelector('#canvas0'),
        ctx = canvas.getContext('2d'),
        width = canvas.width,
        height = canvas.height,
        block_size = 10,
        with_in_blocks = width / block_size,
        height_in_blocks = height / block_size,    
        score = 0,
        intervalId,
        clearRect,
        drawBorder,
        drawScore,
        gameOver;

    drawBorder = function () {
        ctx.fillStyle = 'gray';
        ctx.fillRect(0, 0, width, block_size),
        ctx.fillRect(0, height - block_size, width, block_size);
        ctx.fillRect(0, 0, block_size, height);
        ctx.fillRect(width - block_size, 0, block_size, height);
    };

    drawScore = function () {
        ctx.font = '20px Courier';
        ctx.fillStyle = 'black';
        ctx.textAlign = 'left';
        ctx.textBaseline = 'top';
        ctx.fillText('Score: ' + score, block_size, block_size);
    };

    gameOver = function () {
        clearInterval(intervalId);
        ctx.font = '60px Courier';
        ctx.fillStyle = 'black';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('Game Over', width / 2, height / 2);
    };

    intervalId = setInterval(function () {
        ctx.clearRect(0, 0, width, height);
        drawBorder();
        drawScore();
        score += 1;
    }, 100);

    canvas.onclick = function () {
        clearInterval(intervalId);
        gameOver();
    };
}());

0 コメント:

コメントを投稿