Simple HTML Mario Game - Learn to Code with this Basic Example
<html>
<head>
<title>Simple HTML Mario Game - Learn to Code</title>
<script type="text/javascript">
var mario = {
x: 0,
y: 0,
score: 0
}
<pre><code>function moveMario(direction) {
if (direction == 'left') {
mario.x--;
} else if (direction == 'right') {
mario.x++;
} else if (direction == 'up') {
mario.y--;
} else if (direction == 'down') {
mario.y++;
}
}
function checkCollision(x, y) {
//check if mario is colliding with an obstacle
//return true if there is a collision, false otherwise
if (x == 1 && y == 0) {
return true;
} else {
return false;
}
}
function draw() {
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
//draw mario
ctx.fillStyle = 'green';
ctx.fillRect(mario.x * 50, mario.y * 50, 50, 50);
//draw obstacle
ctx.fillStyle = 'red';
ctx.fillRect(50, 0, 50, 50);
}
function update() {
document.getElementById('score').innerHTML = 'Score: ' + mario.score;
draw();
}
document.onkeydown = function(e) {
if (e.keyCode == 37) {
//left
moveMario('left');
} else if (e.keyCode == 38) {
//up
moveMario('up');
} else if (e.keyCode == 39) {
//right
moveMario('right');
} else if (e.keyCode == 40) {
//down
moveMario('down');
}
if (checkCollision(mario.x, mario.y)) {
mario.score += 10;
}
update();
}
</code></pre>
</script>
</head>
<body>
<canvas id="game" width="300" height="300"></canvas>
<div id="score">Score: 0</div>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmoy 著作权归作者所有。请勿转载和采集!