• 用 p5.js 写个五子棋


    在这里插入图片描述
    之前写 Life Game 时渲染用的是div,这次换 canvas 试试。
    找了个canvas 库 p5i,用起来还可以
    写着玩的,代码还有很多可优化的,懒得弄了。

    代码

    DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <script src="http://unpkg.com/p5i">script>
        <title>五子棋demotitle>
      head>
      <body>
        <div id="target">div>
        <script>
          useWuziqi();
          function useWuziqi({ count = 15 } = {}) {
            const steps = []; // 落子记录 [{ player: Number, position: [x, y] }]
            let nextPlayer = 1; // 1黑棋 2白棋
            let winner; // undefined,1,2
            useUI();
    
            // handle落子
            function onPlayingStoneOnBoard(clickedStone) {
              steps.push({
                player: nextPlayer,
                position: clickedStone,
              });
              if (checkWinning()) {
                winner = nextPlayer;
              } else {
                nextPlayer = 3 - nextPlayer;
              }
            }
    
            function checkWinning() {
              const { player: lastPlayer, position: lastPosition } = steps[steps.length - 1];
              const lastPlayerStepsPositions = steps
                .filter((o) => o.player === lastPlayer)
                .map((o) => o.position);
              function checkCommon(xpianyiliang, ypianyiliang) {
                let count = 1;
                // 向负方向找
                let xSpan = 0;
                let ySpan = 0;
                let flag = true;
                while (flag) {
                  xSpan -= xpianyiliang;
                  ySpan -= ypianyiliang;
                  flag = lastPlayerStepsPositions.find((o) =>
                    isSamePosition(o, [lastPosition[0] + xSpan, lastPosition[1] + ySpan])
                  );
                  if (flag) {
                    count++;
                  }
                }
                // 向正方向找
                xSpan = 0;
                ySpan = 0;
                flag = true;
                while (flag) {
                  xSpan += xpianyiliang;
                  ySpan += ypianyiliang;
                  flag = lastPlayerStepsPositions.find((o) =>
                    isSamePosition(o, [lastPosition[0] + xSpan, lastPosition[1] + ySpan])
                  );
                  if (flag) {
                    count++;
                  }
                }
                return count === 5;
              }
              function checkHorizontal() {
                return checkCommon(0, 1);
              }
              function checkVertical() {
                return checkCommon(1, 0);
              }
              function check_leftTop_to_rightBottom() {
                return checkCommon(1, 1);
              }
              function check_rightTop_to_leftBottom() {
                return checkCommon(-1, 1);
              }
              return (
                checkHorizontal() ||
                checkVertical() ||
                check_leftTop_to_rightBottom() ||
                check_rightTop_to_leftBottom()
              );
            }
    
            function useUI() {
              const boardOffsetX = 40;
              const boardOffsetY = 20;
              const cellSize = 20;
              // get cells positions
              const cellsPositions = [];
              for (let i = 0; i < count; i++) {
                cellsPositions.push([]);
                for (let j = 0; j < count; j++) {
                  cellsPositions[i].push([boardOffsetX + j * cellSize, boardOffsetY + i * cellSize]);
                }
              }
              function drawBoard({ line, rect, circle, fill, stroke }) {
                // 棋盘框和底色
                const boardPadding = 10;
                fill("aliceblue");
                stroke("#ccc");
                rect(
                  boardOffsetX - boardPadding,
                  boardOffsetY - boardPadding,
                  (count - 1) * cellSize + 2 * boardPadding
                );
    
                // 棋盘格子
                for (let i = 0; i < count; i++) {
                  for (let j = 0; j < count; j++) {
                    let y = boardOffsetY + i * cellSize;
                    line(boardOffsetX, y, (count - 1) * cellSize + boardOffsetX, y);
                    let x = boardOffsetX + j * cellSize;
                    line(x, boardOffsetY, x, (count - 1) * cellSize + boardOffsetY);
                  }
                }
    
                // 天元
                fill("#333");
                circle(
                  boardOffsetX + ((count - 1) / 2) * cellSize,
                  boardOffsetY + ((count - 1) / 2) * cellSize,
                  5
                );
              }
              let highlightCell;
              function drawHighlightCross({ fill, rect, noStroke }) {
                if (highlightCell) {
                  const [cellX, cellY] = cellsPositions[highlightCell[0]][highlightCell[1]];
                  noStroke();
                  fill("#535bf2");
                  rect(cellX - 5, cellY - 1, 10, 2);
                  rect(cellX - 1, cellY - 5, 2, 10);
                }
              }
              function drawPlayedStones({ circle, fill, stroke }) {
                steps.forEach((step) => {
                  const [cellX, cellY] = cellsPositions[step.position[0]][step.position[1]];
                  stroke("gray");
                  fill(step.player === 1 ? "black" : "white");
                  circle(cellX, cellY, 15);
                });
              }
              function drawResults({ text, textSize }) {
                if (winner) {
                  textSize(16);
                  text(winner === 1 ? "黑胜" : "白胜", 400, 20);
                }
              }
              function replay() {
                steps.length = 0;
                winner = undefined;
              }
              let button;
              function setup({ createCanvas, createButton }) {
                createCanvas(500, 500);
                button = createButton("REPLAY");
                button.position(380, 50);
                button.mousePressed(replay);
              }
              function draw({
                background,
                rect,
                fill,
                noStroke,
                line,
                stroke,
                circle,
                text,
                textSize,
              }) {
                background("#fafafa");
                noStroke();
                drawBoard({ line, rect, circle, fill, stroke });
                drawHighlightCross({ rect, fill, noStroke });
                drawPlayedStones({ circle, fill, stroke });
                drawResults({ text, textSize });
              }
              function mouseClicked({ mouseX, mouseY }) {
                const clickedStone = findTargetStone({ mouseX, mouseY });
                if (clickedStone) {
                  onPlayingStoneOnBoard(clickedStone);
                }
              }
              function mouseMoved({ mouseX, mouseY }) {
                highlightCell = findTargetStone({ mouseX, mouseY });
              }
    
              P5I.p5i({ setup, draw, mouseClicked, mouseMoved }, document.getElementById("target"));
    
              // 鼠标指向的落子位置
              function findTargetStone({ mouseX, mouseY }) {
                if (winner) return;
                for (let i = 0; i < count; i++) {
                  for (let j = 0; j < count; j++) {
                    const [cellX, cellY] = cellsPositions[i][j];
                    if (Math.pow(cellX - mouseX, 2) + Math.pow(cellY - mouseY, 2) <= 40) {
                      const avaliable = !steps.find((step) => isSamePosition(step.position, [i, j]));
                      if (avaliable) {
                        return [i, j];
                      }
                    }
                  }
                }
                return;
              }
            }
          }
          function isSamePosition(pos1, pos2) {
            return pos1[0] === pos2[0] && pos1[1] === pos2[1];
          }
        script>
      body>
    html>
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
  • 相关阅读:
    15. 三数之和
    xuv自由电子波函数
    数据结构——时间复杂度与空间复杂度
    ubuntu18、20 cv_bridge 与自带opencv版本冲突问题
    【轴承故障诊断】基于matlab贝叶斯优化支持向量机轴承故障诊断(西储数据)【含Matlab源码 2027期】
    猿创征文|盘点刚使用ubuntu时建议下载的软件
    Java项目:SSM医药信息管理系统
    Web1到 Web3,互联网经历了什么?
    开学季征文 | 百尺竿头,我们都要更进一步
    vue+iview中日期时间选择器不能选择当前日期之前包括时分秒
  • 原文地址:https://blog.csdn.net/tangran0526/article/details/126285215