”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Svelte 的扫雷

Svelte 的扫雷

发布于2024-11-01
浏览:995

Background

I never understood as a kid how this game worked, I used to open this game up in Win95 IBM PC, and just click randomly around until I hit a mine. Now that I do, I decided to recreate the game with Svelte.

Lets break it down - How the game works ?

Minesweeper is a single player board game with a goal of clearing all tiles of the board. The player wins if he clicks all the tiles on the board without mines and loses if he clicks on a tile that holds a mine.

Minesweeper in Svelte

Game starts with all tiles concealing what is beneath it, so its a generally a lucky start to the game, you could click on either a empty tile or a mine. In case its not a empty tile or a mine, it could hold a count of mine that are present adjacent to the currently clicked tile.

Minesweeper in Svelte

As an example here 1 at the top left indicates there is 1 mine in of its adjacent cells. Now what do we mean by adjacent cells ? All cells that surround a cell become its adjacent cells. This allows players to strategize about clicking on which tile next. In case a user is not sure whether there is a mine or not underneath a tile, he can flag it by right clicking on the tile.

Minesweeper in Svelte

Thinking about the game logic

The game is pretty simple at first glance, just give a board of n x m rows and keep switching the cell state to display the content that each cell holds. But there is a case where if multiple empty cells are connected and you click on it, the game should keep opening adjacent cells if they are empty too, that gives its iconic ripple effect.

Minesweeper in Svelte

Gets quite tricky building all these conditions in, so lets break down into smaller tasks at hand.

  1. Create a board state - a n x m array (2d array)
  2. A cell inside a board could be / can hold: a mine, a count, or empty.
  3. A cell can be: clicked / not clicked.
  4. A cell can be: flagged / not flagged.
  5. Represent cell with these properties: row, col, text, type(mine, count, empty), clicked(clicked / not clicked), flagged (flagged / not flagged).
  6. Finally we could represent a game state like this: on, win, lose
  7. We also need to have a way to define bounds, while we create that ripple, we don't want the ripple to open up mines too! So we stop open tiles once we hit a boundary of mine!
  8. A game config: row, cols, mine count -> This could help us add difficulty levels to our game easily. Again this is optional step.
  9. This game is just calling a bunch of functions...on click event.

Creating board state

Creating a board is simple task of creating a 2d array given that we know the number of rows and columns. But along with that we also want to put mines at random spots in the board and annotate the board with the mine count in the adjacent cells of mine.

We create a list of unique random indices to put mines at, below function is used to do that,



  function uniqueRandomIndices(
    row_count: number,
    col_count: number,
    range: number,
  ) {
    const upper_row = row_count - 1;
    const upper_col = col_count - 1;
    const idxMap = new Map();
    while (idxMap.size !== range) {
      const rowIdx = Math.floor(Math.random() * upper_row);
      const colIdx = Math.floor(Math.random() * upper_col);
      idxMap.set(`${rowIdx}_${colIdx}`, [rowIdx, colIdx]);
    }
    return [...idxMap.values()];
  }



So here is function that we use to create board state



     function createBoard(
    rows: number,
    cols: number,
    minePositions: Array>,
  ) {
    const minePositionsStrings = minePositions.map(([r, c]) => `${r}_${c}`);
    let boardWithMines = Array.from({ length: rows }, (_, row_idx) =>
      Array.from({ length: cols }, (_, col_idx) => {
        let cell: Cell = {
          text: "",
          row: row_idx,
          col: col_idx,
          type: CellType.empty,
          clicked: CellClickState.not_clicked,
          flagged: FlagState.not_flagged,
        };
        if (minePositionsStrings.includes(`${row_idx}_${col_idx}`)) {
          cell.type = CellType.mine;
          cell.text = CellSymbols.mine;
        }
        return cell;
      }),
    );
    return boardWithMines;
  }



Once we do have a board with mines in random spots, we will end up with a 2d array. Now the important part that makes it possible to play at all, adding mine count to adjacent cells of a mine. For this we have couple of things to keep in mind before we proceed with it.

We have to work within the bounds for any given cell, what are these bounds ?

Bounds here simply means range of rows and cols through which we can iterate through to get all adjacent cells. We need to make sure these bounds never cross the board, else we will get an error or things might not work as expected.

So adjacent cells means each cell that touches current cell on sides or vertices. All the red cells are adjacent cells to the green cell in the middle as per the figure below.

Minesweeper in Svelte


  const getMinIdx = (idx: number) => {
    if (idx > 0) {
      return idx - 1;
    }
    return 0;
  };
  const getMaxIdx = (idx: number, maxLen: number) => {
    if (idx   1 > maxLen - 1) {
      return maxLen - 1;
    }
    return idx   1;
  };

  const getBounds = (row_idx: number, col_idx: number) => {
    return {
      row_min: getMinIdx(row_idx),
      col_min: getMinIdx(col_idx),
      row_max: getMaxIdx(row_idx, rows),
      col_max: getMaxIdx(col_idx, cols),
    };
  };

  function annotateWithMines(
    boardWithMines: Cell[][],
    minePositions: number[][],
  ) {
    for (let minePosition of minePositions) {
      const [row, col] = minePosition;
      const bounds = getBounds(row, col);
      const { row_min, row_max, col_min, col_max } = bounds;
      for (let row_idx = row_min; row_idx 

We now have a board with mines and now we need to display this board with some html/ CSS,



  
{#each board as rows} {#each rows as cell} {/each} {/each}

This renders a grid on page, and certain styles applied conditionally if a cell is clicked, flagged. You get a good old grid like in the screenshot below

Minesweeper in Svelte

Cell and the clicks...

Cell and its state is at the heart of the game. Let's see how to think in terms of various state a cell can have

A cell can have:

  1. Empty content
  2. Mine
  3. Count - adjacent to a mine

A cell can be:

  1. Open
  2. Close

A cell can be:

  1. Flagged
  2. Not Flagged

export enum CellType {
    empty = 0,
    mine = 1,
    count = 2,
}

export enum CellClickState {
    clicked = 0,
    not_clicked = 1,
}
export enum CellSymbols {
    mine = "?",
    flag = "?",
    empty = "",
    explode = "?",
}

export enum FlagState {
    flagged = 0,
    not_flagged = 1,
}

export type Cell = {
    text: string;
    row: number;
    col: number;
    type: CellType;
    clicked: CellClickState;
    flagged: FlagState;
};


Rules for a cell:

  1. On left click, click a cell opens and on a right click cell is flagged.
  2. A flagged cell cannot be opened but only unflagged and then opened.
  3. A click on empty cell should open all its adjacent empty cells until it hits a boundary of mine cells.
  4. A click on cell with mine, should open all the mine with cell and that end the game

With this in mind, we can proceed with implementing a click handler for our cells



 const handleCellClick = (event: MouseEvent) => {
    switch (event.button) {
      case ClickType.left:
        handleLeftClick(event);
        break;
      case ClickType.right:
        handleRightClickonCell(event);
        break;
    }
    return;
  };



Simple enough to understand above function calls respective function mapped to each kind of click , left / right click



  const explodeAllMines = () => {
    for (let [row, col] of minePositions) {
      board[row][col] = {
        ...board[row][col],
        text: CellSymbols.explode,
      };
    }
  };

  const setGameLose = () => {
    game_state = GameState.lose;
  };


  const handleMineClick = () => {
    for (let [row, col] of minePositions) {
      board[row][col] = {
        ...board[row][col],
        clicked: CellClickState.clicked,
      };
    }
    setTimeout(() => {
      explodeAllMines();
      setGameLose();
    }, 300);
  };

  const clickEmptyCell = (row_idx: number, col_idx: number) => {
    // recursively click adjacent cells until:
    // 1. hit a boundary of mine counts - is it same as 3 ?
    // 2. cells are already clicked
    // 3. cells have mines - same as 1 maybe
    // 4. cells that are flagged - need to add a flag feature as well
    if (board[row_idx][col_idx].type === CellType.count) {
      return;
    }

    const { row_min, row_max, col_min, col_max } = getBounds(row_idx, col_idx);
    // loop over bounds to click each cell within the bounds
    for (let r_idx = row_min; r_idx  {
    if (event.target instanceof HTMLButtonElement) {
      const row_idx = Number(event.target.dataset.row);
      const col_idx = Number(event.target.dataset.col);
      const cell = board[row_idx][col_idx];
      if (
        cell.clicked === CellClickState.not_clicked &&
        cell.flagged === FlagState.not_flagged
      ) {
        board[row_idx][col_idx] = {
          ...cell,
          clicked: CellClickState.clicked,
        };
        switch (cell.type) {
          case CellType.mine:
            handleMineClick();
            break;
          case CellType.empty:
            clickEmptyCell(row_idx, col_idx);
            break;
          case CellType.count:
            break;
          default:
            break;
        }
      }
    } else {
      return;
    }
  };


Left click handler - handles most of the game logic, it subdivided into 3 sections based on kind of cell the player clicks on:

  1. Mine cell is clicked on
    If a mine cell is clicked we call handleMineClick() function, that will open up all the mine cells, and after certain timeout we display an explosion icon, we stop the clock and set the game state to lost.

  2. Empty cell is clicked on
    If a empty cell is clicked on we need to recursively click adjacent empty cells until we hit a boundary of first counts. As per the screenshot, you could see when I click on the bottom corner cell, it opens up all the empty cells until the first boundary of counts.

  3. Count cell is clicked on
    Handling count cell is simply revealing the cell content beneath it.

Minesweeper in Svelte

Game state - Final bits and pieces

Game Difficulty can be configured on the basis of ratio of empty cells to mines, if the mines occupy 30% of the board, the game is too difficult for anyone to play, so we set it up incrementally higher up to 25%, which is still pretty high


export const GameDifficulty: Record = {
    baby: { rows: 5, cols: 5, mines: 2, cellSize: "40px" }, // 8% board covered with mines
    normal: { rows: 9, cols: 9, mines: 10, cellSize: "30px" }, // 12% covered with mines
    expert: { rows: 16, cols: 16, mines: 40, cellSize: "27px" }, // 15% covered with mines
    "cheat with an AI": { rows: 16, cols: 46, mines: 180, cellSize: "25px" }, // 25% covered with mines - u need to be only lucky to beat this
};


Game state is divided into 3 states - win, lose and on


export enum GameState {
    on = 0,
    win = 1,
    lose = 2,
}

export type GameConfig = {
    rows: number;
    cols: number;
    mines: number;
    cellSize: string;
};


We also add a timer for the game, that start as soon as the game starts, I have separated it in a timer.worker.js, but it might be an overkill for a small project like this. We also have a function to find the clicked cells count, to check if user has clicked all the cells without mines.


  let { rows, cols, mines, cellSize } = GameDifficulty[difficulty];
  let minePositions = uniqueRandomIndices(rows, cols, mines);
  let game_state: GameState = GameState.on;
  let board = annotateWithMines(
    createBoard(rows, cols, minePositions),
    minePositions,
  );
  let clickedCellsCount = 0;
  let winClickCount = rows * cols - minePositions.length;
  $: flaggedCellsCount = mines;
  $: clickedCellsCount = calculateClickedCellsCount(board);
  $: if (clickedCellsCount === winClickCount) {
    game_state = GameState.win;
  }
  let timer = 0;
  let intervalWorker: Worker;
  let incrementTimer = () => {
    timer  = 1;
  };
  $: if (clickedCellsCount >= 1 && timer === 0) {
    intervalWorker = new Worker("timer.worker.js");
    intervalWorker.addEventListener("message", incrementTimer);
    intervalWorker.postMessage({
      type: "START_TIMER",
      payload: { interval: 1000 },
    });
  }
  $: timerDisplay = {
    minute: Math.round(timer / 60),
    seconds: Math.round(timer % 60),
  };

  $: if (game_state !== GameState.on) {
    intervalWorker?.postMessage({ type: "STOP_TIMER" });
  }

  const calculateClickedCellsCount = (board: Array>) => {
    return board.reduce((acc, arr) => {
      acc  = arr.reduce((count, cell) => {
        count  = cell.clicked === CellClickState.clicked ? 1 : 0;
        return count;
      }, 0);
      return acc;
    }, 0);
  };


And we have got a great minesweeper game now !!!

Minesweeper in Svelte

This is a very basic implementation of Minesweeper, we could do more with it, for starters we could represent the board state with bitmaps, which makes it infinitely...Could be a great coding exercise. Color coding the mine count could be a good detail to have, there are so many things to do with it...this should be a good base to work with...

In case you want to look at the complete code base you could fork / clone the repo from here:

https://github.com/ChinmayMoghe/svelte-minesweeper

版本声明 本文转载于:https://dev.to/chinmaymoghe/minesweeper-in-svelte-21km?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • ## 如何有效分析 PHP 内存使用情况:Xdebug 替代方案和最佳实践
    ## 如何有效分析 PHP 内存使用情况:Xdebug 替代方案和最佳实践
    分析 PHP 内存消耗您寻求一种方法来检查 PHP 页面的内存使用情况。具体来说,您的目标是确定数据的内存分配并识别导致大量内存消耗的函数调用。Xdebug 的限制虽然 Xdebug 提供了跟踪功能,提供内存增量信息,其丰富的数据可能令人难以承受。如果细粒度过滤选项可用,问题就可以得到解决。然而,此...
    编程 发布于2024-11-07
  • 如何在虚拟 DOM 中渲染组件以及如何优化重新渲染
    如何在虚拟 DOM 中渲染组件以及如何优化重新渲染
    构建现代 Web 应用程序时,高效更新 UI(用户界面)对于保持应用程序快速响应至关重要。许多框架(如 React)中使用的常见策略是使用 虚拟 DOM 和 组件。本文将解释如何使用 Virtual DOM 渲染组件,以及如何优化重新渲染以使 Web 应用程序不会变慢。 1.什么是虚...
    编程 发布于2024-11-07
  • CRUD 操作:它们是什么以及如何使用它们?
    CRUD 操作:它们是什么以及如何使用它们?
    CRUD 操作:它们是什么以及如何使用它们? CRUD 操作(创建、读取、更新和删除)是任何需要数据管理的应用程序的基础。对于开发人员来说,了解这些操作非常重要,因为它们提供了我们有效与数据库交互所需的基本功能。在这篇博文中,我将通过展示如何将 CRUD 操作集成到我的 Yoga ...
    编程 发布于2024-11-07
  • 推出免费 Java 实用程序包
    推出免费 Java 实用程序包
    面向 Java 后端开发人员的快速且易于使用的编程工具包 在我作为管理员和开发人员的职业生涯中,我多次从无数的免费软件和开源产品中受益。因此,我很自然地也为这个社区做出贡献。 这个 Java 类集合是在各种项目过程中创建的,并将进一步开发。我希望这个工具也能为您服务。 https://java-ut...
    编程 发布于2024-11-07
  • 如何在 PHP Foreach 循环中检索嵌套数组的数组键?
    如何在 PHP Foreach 循环中检索嵌套数组的数组键?
    PHP:在 Foreach 循环中检索数组键在 PHP 中,使用 foreach 循环迭代关联数组可以访问这两个值和钥匙。但是, key() 函数仅返回当前值的键,这在处理嵌套数组时可能是不够的。例如,考虑这样的数组:<?php $samplearr = array( 4722 =&g...
    编程 发布于2024-11-07
  • 如何将 MySQL 表中的 Latin1 字符转换为 UTF-8?
    如何将 MySQL 表中的 Latin1 字符转换为 UTF-8?
    将 UTF8 表上的 Latin1 字符转换为 UTF8您已确定您的 PHP 脚本缺少必要的 mysql_set_charset 函数以确保正确处理UTF-8 字符。尽管实施了此修复,您现在仍面临着纠正包含存储在 UTF8 表中的 Latin1 字符的现有行的挑战。要解决此问题,您可以利用 MySQ...
    编程 发布于2024-11-07
  • 如何使用 Zapcap API(字幕 API)
    如何使用 Zapcap API(字幕 API)
    将 ZapCap 的自动视频处理 API 集成到您现有的系统中是一个简单的过程,旨在最大限度地降低复杂性并最大限度地提高效率。 ZapCap 提供开发人员友好的 API 文档,以确保无缝入门。 分步集成指南 第 1 步:在 ZapCap 获取您的 API 密钥 在开始之前获...
    编程 发布于2024-11-07
  • 探索引导组件
    探索引导组件
    Bootstrap 5 是最流行的前端框架之一,它带来了一系列有用的组件和实用程序,可帮助开发人员快速构建响应灵敏且具有视觉吸引力的网站。 牌 卡片是 Bootstrap 5 中的多功能组件,可让您以干净、有组织的方式显示内容。它们非常适合以美观且实用的方式展示信息。 ...
    编程 发布于2024-11-07
  • 简化 SVG 管理:将路径转换为单个 JS 常量文件
    简化 SVG 管理:将路径转换为单个 JS 常量文件
    构建 React.js 应用程序时,有效管理 SVG 图标至关重要。 SVG 提供了响应式设计所需的可扩展性和灵活性,但在大型项目中处理它们可能会变得很麻烦。这就是 svg-path-constants 的用武之地,它是一个 CLI 工具,旨在通过将 SVG 路径转换为可重用常量来简化 SVG 工作...
    编程 发布于2024-11-07
  • 如何管理 JavaScript 代码结构
    如何管理 JavaScript 代码结构
    出色地!维护干净且有组织的 JavaScript 代码库对于项目的长期成功至关重要。结构良好的代码库可以增强可读性,减少技术债务,并促进更轻松的调试和扩展。无论您正在开发小型项目还是大型应用程序,遵循构建 JavaScript 代码的最佳实践都可以显着改进您的开发过程。以下是如何管理 JavaScr...
    编程 发布于2024-11-07
  • 溢出可以配置为向左流吗?
    溢出可以配置为向左流吗?
    溢出可以配置为向左流动吗?溢出通常通过强制内容向右流动来处理,导致最左边的内容被裁剪。但是,可以通过应用特定的 CSS 样式来扭转此行为。解决方案要启用向左溢出,请按照给定的步骤操作:将溢出设置为隐藏:将溢出:隐藏应用到容器以防止内容超出其边界。文本右对齐:使用text-align: right将容...
    编程 发布于2024-11-07
  • 如何在保留数据类型的同时将 NumPy 数组与不同数据类型组合?
    如何在保留数据类型的同时将 NumPy 数组与不同数据类型组合?
    在 NumPy 中组合具有多种数据类型的数组将包含不同数据类型的数组连接成单个数组,每列中具有相应的数据类型一个挑战。不幸的是,使用 np.concatenate() 的常见方法会将整个数组转换为字符串数据类型,从而导致内存效率低下。要克服此限制,一个可行的解决方案是使用记录数组或结构化数组。记录数...
    编程 发布于2024-11-07
  • 如何在同一行水平对齐内联块?
    如何在同一行水平对齐内联块?
    在同一行水平对齐内联块问题内联块比浮动元素具有优势,例如基线对齐和自动居中当视口变窄时。然而,在同一行上水平对齐两个内联块可能会带来挑战。内联块对齐的挑战浮动可能会干扰基线对齐并导致不必要的环绕.相对和绝对定位会导致间距问题,类似于浮动。解决方案:使用文本对齐一个有效的解决方案是利用文本对齐: 证明...
    编程 发布于2024-11-07
  • 感到没有动力
    感到没有动力
    感觉自己像个菜鸟,放弃了几次。 我第一次开始考虑编码是在我还是个孩子的时候,但我选择成为一名社交蝴蝶,现在我已经 26 岁了,尝试了很多次学习编码 python、JS、React、DB 等但最终,我感到不知所措并放弃了它。 现在,正因为如此,我感觉自己像个失败的松手,我想解决这个...
    编程 发布于2024-11-07

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3