HTML Mario Game: Play Classic Mario in Your Browser
<html>
<head>
<title>Mario Game: Play Classic Mario in Your Browser</title>
</head>
<body onload='startGame()'>
<h1>Mario Game</h1>
<p>Press the arrow keys to move Mario!</p>
<p><canvas id='canvas' width='400' height='400'></canvas></p>
<script>
//variables for the game
var canvas;
var ctx;
var x = 25;
var y = 25;
var direction;
var squareSize = 50;
var score = 0;
//function to start game
function startGame() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
direction = 'right';
drawMario();
document.addEventListener('keydown', changeDirection);
setInterval(draw, 250);
}
//function to draw Mario
function drawMario() {
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.fillRect(x, y, squareSize, squareSize);
ctx.fill();
ctx.closePath();
}
//function to move Mario
function moveMario() {
switch (direction) {
case 'right':
if (x + squareSize < canvas.width) {
x += squareSize;
score++;
}
break;
case 'left':
if (x > 0) {
x -= squareSize;
score++;
}
break;
case 'up':
if (y > 0) {
y -= squareSize;
score++;
}
break;
case 'down':
if (y + squareSize < canvas.height) {
y += squareSize;
score++;
}
break;
}
}
//function to change direction
function changeDirection(evt) {
var key = evt.keyCode;
switch (key) {
case 37:
direction = 'left';
break;
case 38:
direction = 'up';
break;
case 39:
direction = 'right';
break;
case 40:
direction = 'down';
break;
}
}
//function to draw the game
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawMario();
moveMario();
document.getElementById('score').innerHTML = score;
}
</script>
<p>Score: <span id='score'>0</span></p>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmbI 著作权归作者所有。请勿转载和采集!