用 HTML5 canvas制作一个小游戏生成源代码
时间: 2024-03-10 09:48:13 浏览: 43
HTML5绘图 PDF
4星 · 用户满意度95%
好的,这里提供一个基于 HTML5 canvas 的翻转棋小游戏的源代码,供您参考:
```
<!DOCTYPE html>
<html>
<head>
<title>翻转棋小游戏</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="480" height="480"></canvas>
<script>
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
// 棋盘
var board = [
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, -1, 0, 0, 0],
[0, 0, 0, -1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
];
// 棋子尺寸
var pieceSize = 60;
// 绘制棋盘
function drawBoard() {
ctx.beginPath();
ctx.strokeStyle = "#000";
ctx.lineWidth = 2;
for(var i = 1; i <= 7; i++) {
ctx.moveTo(pieceSize*i, 0);
ctx.lineTo(pieceSize*i, canvas.height);
ctx.moveTo(0, pieceSize*i);
ctx.lineTo(canvas.width, pieceSize*i);
}
ctx.stroke();
ctx.closePath();
}
// 绘制棋子
function drawPiece(row, col, player) {
ctx.beginPath();
ctx.arc(col*pieceSize+pieceSize/2, row*pieceSize+pieceSize/2, pieceSize/2-5, 0, Math.PI*2);
if(player == 1) {
ctx.fillStyle = "#fff";
} else {
ctx.fillStyle = "#000";
}
ctx.fill();
ctx.closePath();
}
// 绘制棋盘和棋子
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBoard();
for(var i = 0; i < 8; i++) {
for(var j = 0; j < 8; j++) {
if(board[i][j] != 0) {
drawPiece(i, j, board[i][j]);
}
}
}
}
// 点击事件
canvas.addEventListener("click", function(e) {
var rect = canvas.getBoundingClientRect();
var row = Math.floor((e.clientY - rect.top) / pieceSize);
var col = Math.floor((e.clientX - rect.left) / pieceSize);
if(board[row][col] != 0) {
return;
}
// 判断落子是否合法
var flag = false;
for(var i = -1; i <= 1; i++) {
for(var j = -1; j <= 1; j++) {
if(i == 0 && j == 0) {
continue;
}
var x = row + i;
var y = col + j;
if(x < 0 || x > 7 || y < 0 || y > 7 || board[x][y] != -board[row][col]) {
continue;
}
x += i;
y += j;
while(x >= 0 && x < 8 && y >= 0 && y < 8) {
if(board[x][y] == 0) {
break;
}
if(board[x][y] == board[row][col]) {
flag = true;
break;
}
x += i;
y += j;
}
}
}
if(flag) {
board[row][col] = board[row][col] == 1 ? -1 : 1;
for(var i = -1; i <= 1; i++) {
for(var j = -1; j <= 1; j++) {
if(i == 0 && j == 0) {
continue;
}
var x = row + i;
var y = col + j;
if(x < 0 || x > 7 || y < 0 || y > 7 || board[x][y] != -board[row][col]) {
continue;
}
var tempList = [];
var x1 = x + i;
var y1 = y + j;
while(x1 >= 0 && x1 < 8 && y1 >= 0 && y1 < 8) {
if(board[x1][y1] == 0) {
break;
}
if(board[x1][y1] == board[row][col]) {
for(var k = 0; k < tempList.length; k++) {
board[tempList[k][0]][tempList[k][1]] = board[tempList[k][0]][tempList[k][1]] == 1 ? -1 : 1;
}
break;
}
tempList.push([x1, y1]);
x1 += i;
y1 += j;
}
}
}
}
draw();
});
draw();
</script>
</body>
</html>
```
这个小游戏实现了一个简单的翻转棋游戏,玩家需要通过点击棋盘上的空位来放置棋子,然后翻转相邻对手的棋子。您可以根据自己的需要进行修改和扩展。
阅读全文