对于HTML5和HTML5来说这是一个很好的第一步吗? JavaScript游戏?

时间:2014-12-11 16:40:02

标签: javascript html5

我重写了一个简单的例子,该例子来自Coursera" Python中的交互式编程简介"在javascript中帮助开始编写HTML游戏。它只允许用户使用箭头键移动球。一个小问题是当同时按下两把钥匙时让球对角移动。

我认为自己是一个中级python程序员,但是一个完整的javascript新手,所以想知道我的解决方案是否太过" pythonic"或者如果有经验的javascript程序员会以同样的方式解决这个问题?

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="c" width="600" height="400"></canvas>
<script>
var canvas, context, ball_pos, vel, keys = {};

var BALL_RADIUS = 20;

function init() {
    'use strict';
    canvas = document.getElementById('c');
    context = canvas.getContext('2d');
    ball_pos = [canvas.width / 2, canvas.height / 2];
    vel = 4;
}

function draw() {
    'use strict';

    // draw background
    context.fillStyle = 'black';
    context.fillRect(0, 0, canvas.width, canvas.height);

    // draw ball
    context.strokeStyle = 'red';
    context.lineWidth = 2;
    context.fillStyle = 'white';
    context.beginPath();
    context.arc(ball_pos[0], ball_pos[1], BALL_RADIUS, 0, Math.PI * 2, true);
    context.closePath();
    context.fill();
    context.stroke();
}

function keydown(evt) {
    'use strict';
    // mozilla based browsers return which and others keyCode
    var keyCode = evt.which || evt.keyCode;
    keys[keyCode] = true;
    if (keys[37] === true) { // left
        ball_pos[0] -= vel;
    }
    if (keys[38] === true) { // up
        ball_pos[1] -= vel;
    }
    if (keys[39] === true) { // right
        ball_pos[0] += vel;
    }
    if (keys[40] === true) { // down
        ball_pos[1] += vel;
    }
}

function keyup(evt) {
    'use strict';
    var keyCode = evt.which || evt.keyCode;
    delete keys[keyCode];
}

function animate() {
    'use strict';
    window.requestAnimationFrame(animate);
    draw();
}

// register event handlers
window.onkeydown = keydown;
window.onkeyup = keyup;

init();
animate();

</script>
</body>
</html>

0 个答案:

没有答案