根据玩家数量构建动态游戏板

Building a dynamic game board based on the number of players

我的朋友正在尝试学习 JS(加上一些 CSS 和 HTML),我们选择从事的项目是制作棋盘游戏。我们尝试构建的棋盘游戏传统上是 4 人游戏(因此是方形棋盘),但是,通过将方形棋盘变成圆形,我们可以缩放棋盘以容纳 n 玩家。游戏很简单,玩家绕着棋盘完成事件(想想垄断)。

目前的计划是根据同时玩游戏的玩家数量来调整棋盘。 4 人游戏有 52 个方块,因此 n 个玩家的棋盘应该有 13n 个方块。

通过查看一些棋盘游戏实现,我们发现最常见的框架是导入棋盘图像或构建 CSS 网格并基于此转换游戏棋子的位置。两者的问题在于它们不是动态的。硬编码多个板然后显示特定的板不是我们想要做的事情。

Rough image of board

实施董事会的最佳做法是什么?

您可以创建一个 canvas,在其上画一个圆圈,然后将该圆圈细分为玩家数量...

const gameboardHeight = 300,
  gameboardWidth = 300;
var numPlayers = 4; // Change for amount of players
const canvas = $('#gameboard')[0]; // Get the canvas
const context = canvas.getContext('2d'); // Get the canvas 'context' to draw on
const slider = $('#players')[0];
slider.addEventListener('input', (e) => {
  numPlayers = parseInt(e.target.value);
  context.clearRect(0, 0, canvas.width, canvas.height);
  renderGameBoard(context, gameboardHeight, gameboardWidth)
})
renderGameBoard(context, gameboardHeight, gameboardWidth);

// Render the game board
function renderGameBoard(ctx, bh, bw) {
  // Center-based coordinates
  function coordsFromCenter(pos, h, w) {
    var centerX = w / 2;
    var centerY = h / 2;
    return vec2(pos.x + centerX, pos.y + centerY);
  }

  // Draw angled line
  function lineAtAngle(pos1, a, r) {
    ctx.beginPath();
    ctx.moveTo(pos1.x, pos1.y);
    ctx.lineTo(pos1.x + r * Math.cos(Math.PI * a / 180.0), pos1.y + r * Math.sin(Math.PI * a / 180.0));
    ctx.stroke();
  }
  // Get the center of the canvas
  let center = coordsFromCenter(vec2(0, 0), bh, bw);
  ctx.beginPath();
  //center x, center y, radius, start angle, end angle (radians)
  ctx.arc(center.x, center.y, Math.min(bh, bw) / 2 - 10, 0, Math.PI * 2);
  ctx.stroke();

  let numSubdivisions = numPlayers * 13;
  let degreesBetweenSubdivisions = 360 / numSubdivisions;
  for (let line = 0; line < numSubdivisions; line++) {
    lineAtAngle(coordsFromCenter(vec2(0, 0), bh, bw), degreesBetweenSubdivisions * (line + 1), Math.min(bh, bw) / 2 - 10);
  }
}

// 2-Axis vector for keeping track of positions
function vec2(x, y) {
  return {
    x: x,
    y: y
  };
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="gameboard" width="300" height="300"></canvas>
<input type="range" id="players" value="4" min="1" max="10" step="1" />