Html canvas 五子棋

<!DOCTYPE html>
<html>
<head>
<title>五子棋</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="width=device-width,initial-scale=1, minimum-scale=1.0, maximum-scale=1, user-scalable=no">
</head>

<body>
    <div style="width:600px;height:600px;background-image:url(images/bg.jpg);">
        <canvas width="600" height="600" onmousedown="play(event)" id="canvas">
        </canvas>
    <div>
</body>
<script type="text/javascript">
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");

bi = new Image();
bi.src = "images/black.png";
wi = new Image();
wi.src = "images/white.png";

var prex = 36, prey = 36, cprex = prex, cprey = prey;
var chess = new Array();
var cnt = 0;
var isFinish = false;

init();

function init() {
    context.clearRect(0, 0, 600, 600);
    for (var i = 0; i < 15; ++i) {
        chess[i] = new Array();
        for (var j = 0; j < 15; ++j) {
            chess[i][j] = 0;
        }
    }
    for (var i = 0; i < 15; ++i) {
        line(prex, prey + i * 38, prex + 14 * 38, prey + i * 38, i == 0 || i == 14);
        line(prex + i * 38, prey, prex + i * 38, prey + 14 * 38, i == 0 || i == 14);
    }
    point(prex + 38 * 3, prey + 38 * 3, 4);    
    point(prex + 38 * 3, prey + 38 * 11, 4);    
    point(prex + 38 * 11, prey + 38 * 3, 4);    
    point(prex + 38 * 11, prey + 38 * 11, 4);    
    point(prex + 38 * 7, prey + 38 * 7, 4);    
    cnt = 0;
    isFinish = false;
}

function windowToCanvas(canvas, x, y) {
    var b = canvas.getBoundingClientRect();
    return {
        x: x - b.left * (canvas.width / b.width),
        y: y - b.top * (canvas.height / b.height)
    };
}

function line(sx, sy, ex, ey, bold) {
    context.beginPath();
    context.moveTo(sx, sy);
    context.lineTo(ex, ey);
    context.strokeStyle = "#000000";
    context.lineWidth = bold ? 4 : 2;
    context.closePath();
    context.stroke();
}

function point(rx, ry, r) {
    context.beginPath();
    context.arc(rx, ry, r, 0, Math.PI * 2, true);
    context.fillStyle = "#000000";
    context.fill();
    context.closePath();
    context.stroke();
}

function play(e) {
    if (isFinish) {
        return;
    }

    var p = windowToCanvas(canvas, e.clientX, e.clientY);
    x = Math.round((p.x - cprex) / 38);
    y = Math.round((p.y - cprey) / 38);
    if (chess[x][y] != 0 || !checkPosition(x, y)) {
        return;
    }
    px = x * 38 + prex - 18;
    py = y * 38 + prey - 18;
    chess[x][y] = cnt % 2 == 0 ? 1 : 2;
    context.drawImage(cnt % 2 == 0 ? wi : bi, px, py);

    if (isEnd(x, y)) {
        isFinished = true;
        show(cnt % 2 != 0 ? "黑方胜" : "白方胜", cnt % 2 != 0 ? "#000000" : "#ffffff");        
        setTimeout("init()", 2000);
    }
    cnt++;
}

function show(ctx, color) {
    context.font = 'bold 72px consolas';
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    context.fillStyle = color;
    context.fillText(ctx, 300, 300);
}

function checkPosition(px, py) {
    return px >= 0 && px < 15 && py >= 0 && py < 15;
}

function isEnd(px, py) {
    return checkDirection(px, py, 0, 1) || checkDirection(px, py, 1, 0) 
        || checkDirection(px, py, -1, -1) || checkDirection(px, py, 1, -1);
}

function checkDirection(px, py, mx, my) {
   var res = 1;
   for (var i = 1; i < 5; ++i) {
      tx = px + i * mx;
      ty = py + i * my;
      if (!checkPosition(tx, ty) || chess[px][py] != chess[tx][ty]) {
          break;
      }
      res++;
   }
   for (var i = 1; i < 5; ++i) {
      tx = px - i * mx;
      ty = py - i * my;
      if (!checkPosition(tx, ty) || chess[px][py] != chess[tx][ty]) {
          break;
      }
      res++;
   }
   return res >= 5;
}

</script>
</html>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在uni-app中使用canvas实现五子棋可以按照以下步骤进行: 1. 创建canvas组件 在需要使用canvas的页面中,添加一个canvas组件: ```html <canvas class="chessboard" canvas-id="canvas"></canvas> ``` 2. 获取canvas上下文 在页面的`onLoad`生命周期函数中,获取canvas的上下文: ```js onLoad() { // 获取canvas上下文 this.ctx = uni.createCanvasContext('canvas', this); } ``` 3. 绘制棋盘 绘制棋盘可以使用`ctx`的绘图API,例如`ctx.beginPath()`、`ctx.moveTo()`、`ctx.lineTo()`等。具体的绘制方法可以参考以下代码: ```js drawChessboard() { const cellWidth = this.data.cellWidth; const boardWidth = this.data.boardWidth; const rows = this.data.rows; const cols = this.data.cols; const margin = this.data.margin; // 绘制棋盘背景 this.ctx.fillStyle = '#D1B18F'; this.ctx.fillRect(0, 0, boardWidth, boardWidth); // 绘制棋盘格线 this.ctx.beginPath(); for (let i = 0; i < rows; i++) { this.ctx.moveTo(margin + cellWidth / 2, margin + i * cellWidth + cellWidth / 2); this.ctx.lineTo(boardWidth - margin - cellWidth / 2, margin + i * cellWidth + cellWidth / 2); } for (let i = 0; i < cols; i++) { this.ctx.moveTo(margin + i * cellWidth + cellWidth / 2, margin + cellWidth / 2); this.ctx.lineTo(margin + i * cellWidth + cellWidth / 2, boardWidth - margin - cellWidth / 2); } this.ctx.stroke(); } ``` 4. 绘制棋子 绘制棋子可以使用`ctx.arc()`和`ctx.fill()`方法实现。具体的绘制方法可以参考以下代码: ```js drawChess(x, y, color) { const cellWidth = this.data.cellWidth; const margin = this.data.margin; const radius = cellWidth / 2 - margin; // 计算棋子的坐标 const cx = margin + x * cellWidth; const cy = margin + y * cellWidth; // 绘制棋子 this.ctx.beginPath(); this.ctx.arc(cx, cy, radius, 0, 2 * Math.PI); this.ctx.fillStyle = color; this.ctx.fill(); } ``` 5. 绑定事件 在canvas上绑定事件可以使用`canvas`组件的`@touchstart`、`@touchmove`、`@touchend`等事件。具体的绑定方法可以参考以下代码: ```html <canvas class="chessboard" canvas-id="canvas" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" ></canvas> ``` 6. 实现游戏逻辑 实现五子棋的游戏逻辑可以在页面的`methods`中进行。例如,判断胜负可以使用一个二维数组来记录棋盘上的棋子,然后通过遍历该数组来判断是否存在连成五个的棋子。具体的实现方法可以参考以下代码: ```js data() { return { // 棋盘格子的宽度 cellWidth: 30, // 棋盘的行数和列数 rows: 15, cols: 15, // 棋盘的宽度 boardWidth: 450, // 棋盘的边缘空白区域 margin: 15, // 棋子的颜色 chessColor: ['white', 'black'], // 当前下棋的玩家 currentPlayer: 0, // 棋盘上的棋子 chessboard: [], // 是否游戏结束 gameOver: false, }; }, onLoad() { this.ctx = uni.createCanvasContext('canvas', this); this.initChessboard(); this.drawChessboard(); }, initChessboard() { // 初始化棋盘 for (let i = 0; i < this.rows; i++) { this.chessboard[i] = []; for (let j = 0; j < this.cols; j++) { this.chessboard[i][j] = -1; } } }, onTouchStart(e) { // 获取触摸点的坐标 const x = e.touches[0].x; const y = e.touches[0].y; // 计算在棋盘中的位置 const i = Math.floor((y - this.data.margin) / this.data.cellWidth); const j = Math.floor((x - this.data.margin) / this.data.cellWidth); // 判断该位置是否为空 if (this.chessboard[i][j] === -1 && !this.gameOver) { // 绘制棋子 this.drawChess(j, i, this.chessColor[this.currentPlayer]); // 记录棋子 this.chessboard[i][j] = this.currentPlayer; // 判断是否胜利 if (this.checkWin(i, j, this.currentPlayer)) { this.gameOver = true; uni.showToast({ title: `玩家${this.currentPlayer + 1}胜利`, icon: 'none' }); return; } // 切换玩家 this.currentPlayer = 1 - this.currentPlayer; } }, checkWin(row, col, player) { const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, 1], [-1, 1], [1, -1]]; for (let i = 0; i < dirs.length; i++) { let count = 1; const dx = dirs[i][0]; const dy = dirs[i][1]; for (let j = 1; j < 5; j++) { const x = row + j * dx; const y = col + j * dy; if (x < 0 || x >= this.rows || y < 0 || y >= this.cols || this.chessboard[x][y] !== player) { break; } count++; } if (count === 5) { return true; } } return false; }, ``` 以上就是在uni-app中使用canvas实现五子棋的步骤,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值