{"id":6491,"date":"2020-06-24T13:47:57","date_gmt":"2020-06-24T13:47:57","guid":{"rendered":"https:\/\/www.askpython.com\/?p=6491"},"modified":"2023-02-16T19:57:04","modified_gmt":"2023-02-16T19:57:04","slug":"create-minesweeper-using-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/create-minesweeper-using-python","title":{"rendered":"Create Minesweeper using Python From the Basic to Advanced"},"content":{"rendered":"\n<p>In this article, we will be going through the steps of creating our own terminal-based Minesweeper using Python Language.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">About the game<\/h2>\n\n\n\n<p>Minesweeper is a single-player game in which the player has to clear a square grid containing mines and numbers. The player has to prevent himself from landing on a mine with the help of numbers in the neighbouring tiles. <\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Gameplay Demo<\/h2>\n\n\n\n<p>Aftermath of few hours of creating a game of Minesweeper.<\/p>\n\n\n\n<figure class=\"wp-block-video aligncenter\"><video height=\"768\" style=\"aspect-ratio: 1366 \/ 768;\" width=\"1366\" controls src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/06\/minesweeper-1.mp4\"><\/video><figcaption>Minesweeper Demo<\/figcaption><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Designing Minesweeper Using Python<\/h2>\n\n\n\n<p>Before creating the game logic, we need to design the basic layout of the game. A square grid is rather easy to create using Python by: <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Printing the Minesweeper Layout\ndef print_mines_layout():\n\tglobal mine_values\n\tglobal n\n\n\tprint()\n\tprint(&quot;\\t\\t\\tMINESWEEPER\\n&quot;)\n\n\tst = &quot;   &quot;\n\tfor i in range(n):\n\t\tst = st + &quot;     &quot; + str(i + 1)\n\tprint(st)\t\n\n\tfor r in range(n):\n\t\tst = &quot;     &quot;\n\t\tif r == 0:\n\t\t\tfor col in range(n):\n\t\t\t\tst = st + &quot;______&quot;\t\n\t\t\tprint(st)\n\n\t\tst = &quot;     &quot;\n\t\tfor col in range(n):\n\t\t\tst = st + &quot;|     &quot;\n\t\tprint(st + &quot;|&quot;)\n\t\t\n\t\tst = &quot;  &quot; + str(r + 1) + &quot;  &quot;\n\t\tfor col in range(n):\n\t\t\tst = st + &quot;|  &quot; + str(mine_values&#x5B;r]&#x5B;col]) + &quot;  &quot;\n\t\tprint(st + &quot;|&quot;)\t\n\n\t\tst = &quot;     &quot;\n\t\tfor col in range(n):\n\t\t\tst = st + &quot;|_____&quot;\n\t\tprint(st + &#039;|&#039;)\n\n\tprint()\n<\/pre><\/div>\n\n\n<p>The grid displayed in each iteration resembles the following figure:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"549\" height=\"538\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/06\/minesweeper_layout.png\" alt=\"Minesweeper Layout\" class=\"wp-image-6492\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/06\/minesweeper_layout.png 549w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/06\/minesweeper_layout-300x294.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/06\/minesweeper_layout-24x24.png 24w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/06\/minesweeper_layout-48x48.png 48w\" sizes=\"auto, (max-width: 549px) 100vw, 549px\" \/><figcaption>Minesweeper Layout<\/figcaption><\/figure><\/div>\n\n\n\n<p>The <code>'M'<\/code> symbol denotes the presence of a &#8216;mine&#8217; in that cell. As we can see clearly, any number on the grid denotes the number of mines present in the neighbouring &#8216;eight&#8217; cells. <\/p>\n\n\n\n<p>The use of variables like, <code>mine_values<\/code> will be explained further in the tutorial. <\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Input system<\/h2>\n\n\n\n<p>One of the most important parts of any game is sustaining the input method. In our version of Minesweeper, we will be using the row and column numbers for our input technique.<\/p>\n\n\n\n<p>Before starting the game, the script must provide a set of instructions for the player. Our game prints the following. <\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"66\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/06\/minesweeper_instructions.png\" alt=\"Minesweeper Instructions\" class=\"wp-image-6493\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/06\/minesweeper_instructions.png 750w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/06\/minesweeper_instructions-300x26.png 300w\" sizes=\"auto, (max-width: 750px) 100vw, 750px\" \/><figcaption>Minesweeper Instructions<\/figcaption><\/figure><\/div>\n\n\n\n<p>The row and column numbers displayed along with the grid are helpful for our input system. As we know, keeping track of mines without any indicator can be difficult. Therefore, Minesweeper has a provision of using &#8216;flag&#8217; to mark the cells, which we know contains a mine.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Data Storage  <\/h2>\n\n\n\n<p>For a single game of Minesweeper, we need to keep track of the following information:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The <strong>size<\/strong> of the grid.<\/li><li>The <strong>number of mines<\/strong>.<\/li><li><strong>The &#8216;actual&#8217; grid values<\/strong> &#8211; At the start of the game, we need a container for storing the real values for the game, unknown to the player. For instance, the location of mines.<\/li><li><strong>The &#8216;apparent&#8217; grid values<\/strong> &#8211; After each move, we need to update all the values that must be shown to the player. <\/li><li><strong>The flagged positions<\/strong> &#8211; The cells which have been flagged. <\/li><\/ul>\n\n\n\n<p>These values are stored using the following data structures<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nif __name__ == &quot;__main__&quot;:\n\n\t# Size of grid\n\tn = 8\n\t# Number of mines\n\tmines_no = 8\n\n\t# The actual values of the grid\n\tnumbers = &#x5B;&#x5B;0 for y in range(n)] for x in range(n)] \n\t# The apparent values of the grid\n\tmine_values = &#x5B;&#x5B;&#039; &#039; for y in range(n)] for x in range(n)]\n\t# The positions that have been flagged\n\tflags = &#x5B;]\n<\/pre><\/div>\n\n\n<p>There is not much in the game-logic of Minesweeper. All the effort is to be done in setting up the Minesweeper layout.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Setting up the Mines<\/h2>\n\n\n\n<p>We need to set up the positions of the mines randomly, so that the player might not predict their positions. This can be done by:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Function for setting up Mines\ndef set_mines():\n\n\tglobal numbers\n\tglobal mines_no\n\tglobal n\n\n\t# Track of number of mines already set up\n\tcount = 0\n\twhile count &lt; mines_no:\n\n\t\t# Random number from all possible grid positions \n\t\tval = random.randint(0, n*n-1)\n\n\t\t# Generating row and column from the number\n\t\tr = val \/\/ n\n\t\tcol = val % n\n\n\t\t# Place the mine, if it doesn&#039;t already have one\n\t\tif numbers&#x5B;r]&#x5B;col] != -1:\n\t\t\tcount = count + 1\n\t\t\tnumbers&#x5B;r]&#x5B;col] = -1\n<\/pre><\/div>\n\n\n<p>In the code, we choose a random number from all possible cells in the grid. We keep doing this until we get the said number of mines.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><strong>Note:<\/strong> The actual value for a mine is stored as -1, whereas the values stored for display, denote the mine as <code>'M'<\/code>. <\/p><p><strong>Note:<\/strong> The <a href=\"https:\/\/www.askpython.com\/python-modules\/python-randint-method\" class=\"rank-math-link\">&#8216;randint&#8217;<\/a> function can only be used after importing the random library. It is done by writing <code>'import random'<\/code> at the start of the program. <\/p><\/blockquote>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Setting up the grid numbers<\/h2>\n\n\n\n<p>For each cell in the grid, we have to check all adjacent neighbours whether there is a mine present or not. This is done by:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Function for setting up the other grid values\ndef set_values():\n\n\tglobal numbers\n\tglobal n\n\n\t# Loop for counting each cell value\n\tfor r in range(n):\n\t\tfor col in range(n):\n\n\t\t\t# Skip, if it contains a mine\n\t\t\tif numbers&#x5B;r]&#x5B;col] == -1:\n\t\t\t\tcontinue\n\n\t\t\t# Check up\t\n\t\t\tif r &gt; 0 and numbers&#x5B;r-1]&#x5B;col] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check down\t\n\t\t\tif r &lt; n-1  and numbers&#x5B;r+1]&#x5B;col] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check left\n\t\t\tif col &gt; 0 and numbers&#x5B;r]&#x5B;col-1] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;c] = numbers&#x5B;r]&#x5B;c] + 1\n\t\t\t# Check right\n\t\t\tif col &lt; n-1 and numbers&#x5B;r]&#x5B;col+1] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check top-left\t\n\t\t\tif r &gt; 0 and col &gt; 0 and numbers&#x5B;r-1]&#x5B;col-1] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check top-right\n\t\t\tif r &gt; 0 and col &lt; n-1 and numbers&#x5B;r-1]&#x5B;col+1]== -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check below-left\t\n\t\t\tif r &lt; n-1 and col &gt; 0 and numbers&#x5B;r+1]&#x5B;col-1]== -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check below-right\n\t\t\tif r &lt; n-1 and col&lt; n-1 and numbers&#x5B;r+1]&#x5B;col+1]==-1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n<\/pre><\/div>\n\n\n<p>These values are to be hidden from the player, therefore they are stored in <code>numbers<\/code> variable. <\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Game Loop<\/h2>\n\n\n\n<p>Game Loop is a very crucial part of the game. It is needed to update every move of the player as well as the conclusion of the game. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Set the mines\nset_mines()\n\n# Set the values\nset_values()\n\n# Display the instructions\ninstructions()\n\n# Variable for maintaining Game Loop\nover = False\n\t\t\n# The GAME LOOP\t\nwhile not over:\n\tprint_mines_layout()\n<\/pre><\/div>\n\n\n<p>In each iteration of the loop, the Minesweeper grid must be displayed as well as the player&#8217;s move must be handled. <\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Handle the player input<\/h2>\n\n\n\n<p>As we mentioned before, there are two kinds of player input :<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Input from the user\ninp = input(&quot;Enter row number followed by space and column number = &quot;).split()\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Standard input<\/h3>\n\n\n\n<p>In a normal kind of move, the row and column number are mentioned. The player&#8217;s motive behind this move is to unlock a cell that does not contain a mine. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Standard Move\nif len(inp) == 2:\n\n\t# Try block to handle errant input\n\ttry: \n\t\tval = list(map(int, inp))\n\texcept ValueError:\n\t\tclear()\n\t\tprint(&quot;Wrong input!&quot;)\n\t\tinstructions()\n\t\tcontinue\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Flag input<\/h3>\n\n\n\n<p>In a flagging move, three values are sent in by the gamer. The first two values denote cell location, while the last one denotes flagging.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Flag Input\nelif len(inp) == 3:\n\tif inp&#x5B;2] != &#039;F&#039; and inp&#x5B;2] != &#039;f&#039;:\n\t\tclear()\n\t\tprint(&quot;Wrong Input!&quot;)\n\t\tinstructions()\n\t\tcontinue\n\n\t# Try block to handle errant input\t\n\ttry:\n\t\tval = list(map(int, inp&#x5B;:2]))\n\texcept ValueError:\n\t\tclear()\n\t\tprint(&quot;Wrong input!&quot;)\n\t\tinstructions()\n\t\tcontinue\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Sanitize the input<\/h2>\n\n\n\n<p>After storing the input, we have to do some sanity checks, for the smooth functioning of the game.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Sanity checks\nif val&#x5B;0] &gt; n or val&#x5B;0] &lt; 1 or val&#x5B;1] &gt; n or val&#x5B;1] &lt; 1:\n\tclear()\n\tprint(&quot;Wrong Input!&quot;)\n\tinstructions()\n\tcontinue\n\n# Get row and column numbers\nr = val&#x5B;0]-1\ncol = val&#x5B;1]-1\n<\/pre><\/div>\n\n\n<p>On the completion of input process, the row and column numbers are to be extracted and stored in <code>'r'<\/code> and <code>'c'<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Handle the flag input<\/h2>\n\n\n\n<p>Managing the flag input is not a big issue. It requires checking for some pre-requisites before flagging the cell for a mine.<\/p>\n\n\n\n<p>The following checks must be made:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The cell has already been flagged or not.<\/li><li>Whether the cell to be flagged is already displayed to the player.<\/li><li>The number of flags does not exceed the number of mines.<\/li><\/ul>\n\n\n\n<p>After taking care of these issues, the cell is flagged for a mine. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# If cell already been flagged\nif &#x5B;r, col] in flags:\n\tclear()\n\tprint(&quot;Flag already set&quot;)\n\tcontinue\n\n# If cell already been displayed\nif mine_values&#x5B;r]&#x5B;col] != &#039; &#039;:\n\tclear()\n\tprint(&quot;Value already known&quot;)\n\tcontinue\n\n# Check the number for flags \t\nif len(flags) &lt; mines_no:\n\tclear()\n\tprint(&quot;Flag set&quot;)\n\n\t# Adding flag to the list\n\tflags.append(&#x5B;r, col])\n\t\n\t# Set the flag for display\n\tmine_values&#x5B;r]&#x5B;col] = &#039;F&#039;\n\tcontinue\nelse:\n\tclear()\n\tprint(&quot;Flags finished&quot;)\n\tcontinue\t \n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Handle the standard input<\/h2>\n\n\n\n<p>The standard input involves the overall functioning of the game. There are three different scenarios:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Anchoring on a mine<\/h3>\n\n\n\n<p>The game is finished as soon as the player selects a cell having a mine. It can happen out of bad luck or poor judgment. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# If landing on a mine --- GAME OVER\t\nif numbers&#x5B;r]&#x5B;col] == -1:\n\tmine_values&#x5B;r]&#x5B;col] = &#039;M&#039;\n\tshow_mines()\n\tprint_mines_layout()\n\tprint(&quot;Landed on a mine. GAME OVER!!!!!&quot;)\n\tover = True\n\tcontinue\n<\/pre><\/div>\n\n\n<p>After we land on a cell with mine, we need to display all the mines in the game and alter the variable behind the game loop.<\/p>\n\n\n\n<p>The function <code>'show_mines()'<\/code> is responsible for it.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef show_mines():\n\tglobal mine_values\n\tglobal numbers\n\tglobal n\n\n\tfor r in range(n):\n\t\tfor col in range(n):\n\t\t\tif numbers&#x5B;r]&#x5B;col] == -1:\n\t\t\t\tmine_values&#x5B;r]&#x5B;col] = &#039;M&#039;\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Visiting a &#8216;0&#8217;-valued cell.<\/h3>\n\n\n\n<p>The trickiest part of creating the game is managing this scenario. Whenever a gamer, visits a &#8216;0&#8217;-valued cell, all the neighboring elements must be displayed until a non-zero-valued cell is reached. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# If landing on a cell with 0 mines in neighboring cells\nelif numbers&#x5B;r]&#x5B;n] == 0:\n\tvis = &#x5B;]\n\tmine_values&#x5B;r]&#x5B;n] = &#039;0&#039;\n\tneighbours(r, col)\t\n<\/pre><\/div>\n\n\n<p>This objective is achieved using <strong><a href=\"https:\/\/www.askpython.com\/python\/python-recursion-function\" class=\"rank-math-link\">Recursion<\/a><\/strong>. Recursion is a programming tool in which the function calls itself until the base case is satisfied. The <code>neighbours<\/code> function is a recursive one, solving our problem.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef neighbours(r, col):\n\t\n\tglobal mine_values\n\tglobal numbers\n\tglobal vis\n\n\t# If the cell already not visited\n\tif &#x5B;r,col] not in vis:\n\n\t\t# Mark the cell visited\n\t\tvis.append(&#x5B;r,col])\n\n\t\t# If the cell is zero-valued\n\t\tif numbers&#x5B;r]&#x5B;col] == 0:\n\n\t\t\t# Display it to the user\n\t\t\tmine_values&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col]\n\n\t\t\t# Recursive calls for the neighbouring cells\n\t\t\tif r &gt; 0:\n\t\t\t\tneighbours(r-1, col)\n\t\t\tif r &lt; n-1:\n\t\t\t\tneighbours(r+1, col)\n\t\t\tif col &gt; 0:\n\t\t\t\tneighbours(r, col-1)\n\t\t\tif col &lt; n-1:\n\t\t\t\tneighbours(r, col+1)\t\n\t\t\tif r &gt; 0 and col &gt; 0:\n\t\t\t\tneighbours(r-1, col-1)\n\t\t\tif r &gt; 0 and col &lt; n-1:\n\t\t\t\tneighbours(r-1, col+1)\n\t\t\tif r &lt; n-1 and col &gt; 0:\n\t\t\t\tneighbours(r+1, col-1)\n\t\t\tif r &lt; n-1 and col &lt; n-1:\n\t\t\t\tneighbours(r+1, col+1)\t\n\t\t\t\t\n\t\t# If the cell is not zero-valued \t\t\t\n\t\tif numbers&#x5B;r]&#x5B;col] != 0:\n\t\t\t\tmine_values&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col]\n<\/pre><\/div>\n\n\n<p>For this particular concept of the game, a new data structure is used, namely, <code>vis<\/code>. The role of <code>vis<\/code> to keep track of already visited cells during recursion. Without this information, the recursion will continue perpetually. <\/p>\n\n\n\n<p>After all the cells with zero value and their neighbours are displayed, we can move on to the last scenario.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Choosing a non zero-valued cell<\/h3>\n\n\n\n<p>No effort is needed to handle this case, as all we need to do is alter the displaying value.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# If selecting a cell with atleast 1 mine in neighboring cells\t\nelse:\t\n\tmine_values&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col]\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">End game<\/h2>\n\n\n\n<p>There is a requirement to check for completion of the game, each time a move is made. This is done by:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Check for game completion\t\nif(check_over()):\n\tshow_mines()\n\tprint_mines_layout()\n\tprint(&quot;Congratulations!!! YOU WIN&quot;)\n\tover = True\n\tcontinue\n<\/pre><\/div>\n\n\n<p>The function <code>check_over()<\/code>, is responsible for checking the completion of the game.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Function to check for completion of the game\ndef check_over():\n\tglobal mine_values\n\tglobal n\n\tglobal mines_no\n\n\t# Count of all numbered values\n\tcount = 0\n\n\t# Loop for checking each cell in the grid\n\tfor r in range(n):\n\t\tfor col in range(n):\n\n\t\t\t# If cell not empty or flagged\n\t\t\tif mine_values&#x5B;r]&#x5B;col] != &#039; &#039; and mine_values&#x5B;r]&#x5B;col] != &#039;F&#039;:\n\t\t\t\tcount = count + 1\n\t\n\t# Count comparison \t\t\t\n\tif count == n * n - mines_no:\n\t\treturn True\n\telse:\n\t\treturn False\n<\/pre><\/div>\n\n\n<p>We count the number of cells, that are not empty or flagged. When this count is equal to the total cells, except those containing mines, then the game is regarded as over.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Clearing output after each move<\/h2>\n\n\n\n<p>The terminal becomes crowded as we keep on printing stuff on it. Therefore, there must be provision for clearing it constantly. This can be done by: <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Function for clearing the terminal\ndef clear():\n\tos.system(&quot;clear&quot;)\n<\/pre><\/div>\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><strong>Note:<\/strong> There is a need to import the <code>os<\/code> library, before using this feature. It can be done by <code>'import os'<\/code> at the start of the program.<\/p><\/blockquote>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">The complete code<\/h2>\n\n\n\n<p>Below is the complete code of the Minesweeper game:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Importing packages\nimport random\nimport os\n\n# Printing the Minesweeper Layout\ndef print_mines_layout():\n\n\tglobal mine_values\n\tglobal n\n\n\tprint()\n\tprint(&quot;\\t\\t\\tMINESWEEPER\\n&quot;)\n\n\tst = &quot;   &quot;\n\tfor i in range(n):\n\t\tst = st + &quot;     &quot; + str(i + 1)\n\tprint(st)\t\n\n\tfor r in range(n):\n\t\tst = &quot;     &quot;\n\t\tif r == 0:\n\t\t\tfor col in range(n):\n\t\t\t\tst = st + &quot;______&quot;\t\n\t\t\tprint(st)\n\n\t\tst = &quot;     &quot;\n\t\tfor col in range(n):\n\t\t\tst = st + &quot;|     &quot;\n\t\tprint(st + &quot;|&quot;)\n\t\t\n\t\tst = &quot;  &quot; + str(r + 1) + &quot;  &quot;\n\t\tfor col in range(n):\n\t\t\tst = st + &quot;|  &quot; + str(mine_values&#x5B;r]&#x5B;col]) + &quot;  &quot;\n\t\tprint(st + &quot;|&quot;)\t\n\n\t\tst = &quot;     &quot;\n\t\tfor col in range(n):\n\t\t\tst = st + &quot;|_____&quot;\n\t\tprint(st + &#039;|&#039;)\n\n\tprint()\n \n# Function for setting up Mines\ndef set_mines():\n\n\tglobal numbers\n\tglobal mines_no\n\tglobal n\n\n\t# Track of number of mines already set up\n\tcount = 0\n\twhile count &lt; mines_no:\n\n\t\t# Random number from all possible grid positions \n\t\tval = random.randint(0, n*n-1)\n\n\t\t# Generating row and column from the number\n\t\tr = val \/\/ n\n\t\tcol = val % n\n\n\t\t# Place the mine, if it doesn&#039;t already have one\n\t\tif numbers&#x5B;r]&#x5B;col] != -1:\n\t\t\tcount = count + 1\n\t\t\tnumbers&#x5B;r]&#x5B;col] = -1\n\n# Function for setting up the other grid values\ndef set_values():\n\n\tglobal numbers\n\tglobal n\n\n\t# Loop for counting each cell value\n\tfor r in range(n):\n\t\tfor col in range(n):\n\n\t\t\t# Skip, if it contains a mine\n\t\t\tif numbers&#x5B;r]&#x5B;col] == -1:\n\t\t\t\tcontinue\n\n\t\t\t# Check up\t\n\t\t\tif r &gt; 0 and numbers&#x5B;r-1]&#x5B;col] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check down\t\n\t\t\tif r &lt; n-1  and numbers&#x5B;r+1]&#x5B;col] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check left\n\t\t\tif col &gt; 0 and numbers&#x5B;r]&#x5B;col-1] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check right\n\t\t\tif col &lt; n-1 and numbers&#x5B;r]&#x5B;col+1] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check top-left\t\n\t\t\tif r &gt; 0 and col &gt; 0 and numbers&#x5B;r-1]&#x5B;col-1] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check top-right\n\t\t\tif r &gt; 0 and col &lt; n-1 and numbers&#x5B;r-1]&#x5B;col+1] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check below-left\t\n\t\t\tif r &lt; n-1 and col &gt; 0 and numbers&#x5B;r+1]&#x5B;col-1] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\t\t\t# Check below-right\n\t\t\tif r &lt; n-1 and col &lt; n-1 and numbers&#x5B;r+1]&#x5B;col+1] == -1:\n\t\t\t\tnumbers&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col] + 1\n\n# Recursive function to display all zero-valued neighbours\t\ndef neighbours(r, col):\n\t\n\tglobal mine_values\n\tglobal numbers\n\tglobal vis\n\n\t# If the cell already not visited\n\tif &#x5B;r,col] not in vis:\n\n\t\t# Mark the cell visited\n\t\tvis.append(&#x5B;r,col])\n\n\t\t# If the cell is zero-valued\n\t\tif numbers&#x5B;r]&#x5B;col] == 0:\n\n\t\t\t# Display it to the user\n\t\t\tmine_values&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col]\n\n\t\t\t# Recursive calls for the neighbouring cells\n\t\t\tif r &gt; 0:\n\t\t\t\tneighbours(r-1, col)\n\t\t\tif r &lt; n-1:\n\t\t\t\tneighbours(r+1, col)\n\t\t\tif col &gt; 0:\n\t\t\t\tneighbours(r, col-1)\n\t\t\tif col &lt; n-1:\n\t\t\t\tneighbours(r, col+1)\t\n\t\t\tif r &gt; 0 and col &gt; 0:\n\t\t\t\tneighbours(r-1, col-1)\n\t\t\tif r &gt; 0 and col &lt; n-1:\n\t\t\t\tneighbours(r-1, col+1)\n\t\t\tif r &lt; n-1 and col &gt; 0:\n\t\t\t\tneighbours(r+1, col-1)\n\t\t\tif r &lt; n-1 and col &lt; n-1:\n\t\t\t\tneighbours(r+1, col+1)\t\n\n\t\t# If the cell is not zero-valued \t\t\t\n\t\tif numbers&#x5B;r]&#x5B;col] != 0:\n\t\t\t\tmine_values&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col]\n\n# Function for clearing the terminal\ndef clear():\n\tos.system(&quot;clear&quot;)\t\t\n\n# Function to display the instructions\ndef instructions():\n\tprint(&quot;Instructions:&quot;)\n\tprint(&quot;1. Enter row and column number to select a cell, Example \\&quot;2 3\\&quot;&quot;)\n\tprint(&quot;2. In order to flag a mine, enter F after row and column numbers, Example \\&quot;2 3 F\\&quot;&quot;)\n\n# Function to check for completion of the game\ndef check_over():\n\tglobal mine_values\n\tglobal n\n\tglobal mines_no\n\n\t# Count of all numbered values\n\tcount = 0\n\n\t# Loop for checking each cell in the grid\n\tfor r in range(n):\n\t\tfor col in range(n):\n\n\t\t\t# If cell not empty or flagged\n\t\t\tif mine_values&#x5B;r]&#x5B;col] != &#039; &#039; and mine_values&#x5B;r]&#x5B;col] != &#039;F&#039;:\n\t\t\t\tcount = count + 1\n\t\n\t# Count comparison \t\t\t\n\tif count == n * n - mines_no:\n\t\treturn True\n\telse:\n\t\treturn False\n\n# Display all the mine locations\t\t\t\t\t\ndef show_mines():\n\tglobal mine_values\n\tglobal numbers\n\tglobal n\n\n\tfor r in range(n):\n\t\tfor col in range(n):\n\t\t\tif numbers&#x5B;r]&#x5B;col] == -1:\n\t\t\t\tmine_values&#x5B;r]&#x5B;col] = &#039;M&#039;\n\n\nif __name__ == &quot;__main__&quot;:\n\n\t# Size of grid\n\tn = 8\n\t# Number of mines\n\tmines_no = 8\n\n\t# The actual values of the grid\n\tnumbers = &#x5B;&#x5B;0 for y in range(n)] for x in range(n)] \n\t# The apparent values of the grid\n\tmine_values = &#x5B;&#x5B;&#039; &#039; for y in range(n)] for x in range(n)]\n\t# The positions that have been flagged\n\tflags = &#x5B;]\n\n\t# Set the mines\n\tset_mines()\n\n\t# Set the values\n\tset_values()\n\n\t# Display the instructions\n\tinstructions()\n\n\t# Variable for maintaining Game Loop\n\tover = False\n\t\t\n\t# The GAME LOOP\t\n\twhile not over:\n\t\tprint_mines_layout()\n\n\t\t# Input from the user\n\t\tinp = input(&quot;Enter row number followed by space and column number = &quot;).split()\n\t\t\n\t\t# Standard input\n\t\tif len(inp) == 2:\n\n\t\t\t# Try block to handle errant input\n\t\t\ttry: \n\t\t\t\tval = list(map(int, inp))\n\t\t\texcept ValueError:\n\t\t\t\tclear()\n\t\t\t\tprint(&quot;Wrong input!&quot;)\n\t\t\t\tinstructions()\n\t\t\t\tcontinue\n\n\t\t# Flag input\n\t\telif len(inp) == 3:\n\t\t\tif inp&#x5B;2] != &#039;F&#039; and inp&#x5B;2] != &#039;f&#039;:\n\t\t\t\tclear()\n\t\t\t\tprint(&quot;Wrong Input!&quot;)\n\t\t\t\tinstructions()\n\t\t\t\tcontinue\n\n\t\t\t# Try block to handle errant input\t\n\t\t\ttry:\n\t\t\t\tval = list(map(int, inp&#x5B;:2]))\n\t\t\texcept ValueError:\n\t\t\t\tclear()\n\t\t\t\tprint(&quot;Wrong input!&quot;)\n\t\t\t\tinstructions()\n\t\t\t\tcontinue\n\n\t\t\t# Sanity checks\t\n\t\t\tif val&#x5B;0] &gt; n or val&#x5B;0] &lt; 1 or val&#x5B;1] &gt; n or val&#x5B;1] &lt; 1:\n\t\t\t\tclear()\n\t\t\t\tprint(&quot;Wrong input!&quot;)\n\t\t\t\tinstructions()\n\t\t\t\tcontinue\n\n\t\t\t# Get row and column numbers\n\t\t\tr = val&#x5B;0]-1\n\t\t\tcol = val&#x5B;1]-1\t\n\n\t\t\t# If cell already been flagged\n\t\t\tif &#x5B;r, col] in flags:\n\t\t\t\tclear()\n\t\t\t\tprint(&quot;Flag already set&quot;)\n\t\t\t\tcontinue\n\n\t\t\t# If cell already been displayed\n\t\t\tif mine_values&#x5B;r]&#x5B;col] != &#039; &#039;:\n\t\t\t\tclear()\n\t\t\t\tprint(&quot;Value already known&quot;)\n\t\t\t\tcontinue\n\n\t\t\t# Check the number for flags \t\n\t\t\tif len(flags) &lt; mines_no:\n\t\t\t\tclear()\n\t\t\t\tprint(&quot;Flag set&quot;)\n\n\t\t\t\t# Adding flag to the list\n\t\t\t\tflags.append(&#x5B;r, col])\n\t\t\t\t\n\t\t\t\t# Set the flag for display\n\t\t\t\tmine_values&#x5B;r]&#x5B;col] = &#039;F&#039;\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tclear()\n\t\t\t\tprint(&quot;Flags finished&quot;)\n\t\t\t\tcontinue\t \n\n\t\telse: \n\t\t\tclear()\n\t\t\tprint(&quot;Wrong input!&quot;)\t\n\t\t\tinstructions()\n\t\t\tcontinue\n\t\t\t\n\n\t\t# Sanity checks\n\t\tif val&#x5B;0] &gt; n or val&#x5B;0] &lt; 1 or val&#x5B;1] &gt; n or val&#x5B;1] &lt; 1:\n\t\t\tclear()\n\t\t\tprint(&quot;Wrong Input!&quot;)\n\t\t\tinstructions()\n\t\t\tcontinue\n\t\t\t\n\t\t# Get row and column number\n\t\tr = val&#x5B;0]-1\n\t\tcol = val&#x5B;1]-1\n\n\t\t# Unflag the cell if already flagged\n\t\tif &#x5B;r, col] in flags:\n\t\t\tflags.remove(&#x5B;r, col])\n\n\t\t# If landing on a mine --- GAME OVER\t\n\t\tif numbers&#x5B;r]&#x5B;col] == -1:\n\t\t\tmine_values&#x5B;r]&#x5B;col] = &#039;M&#039;\n\t\t\tshow_mines()\n\t\t\tprint_mines_layout()\n\t\t\tprint(&quot;Landed on a mine. GAME OVER!!!!!&quot;)\n\t\t\tover = True\n\t\t\tcontinue\n\n\t\t# If landing on a cell with 0 mines in neighboring cells\n\t\telif numbers&#x5B;r]&#x5B;col] == 0:\n\t\t\tvis = &#x5B;]\n\t\t\tmine_values&#x5B;r]&#x5B;col] = &#039;0&#039;\n\t\t\tneighbours(r, col)\n\n\t\t# If selecting a cell with atleast 1 mine in neighboring cells\t\n\t\telse:\t\n\t\t\tmine_values&#x5B;r]&#x5B;col] = numbers&#x5B;r]&#x5B;col]\n\n\t\t# Check for game completion\t\n\t\tif(check_over()):\n\t\t\tshow_mines()\n\t\t\tprint_mines_layout()\n\t\t\tprint(&quot;Congratulations!!! YOU WIN&quot;)\n\t\t\tover = True\n\t\t\tcontinue\n\t\tclear()\t\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-very-dark-gray-background-color has-very-dark-gray-color is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>We hope that this tutorial on creating our own Minesweeper game was understandable as well as fun. For any queries, feel free to comment below. The complete code is also available on my <a aria-label=\" Github account (opens in a new tab)\" href=\"https:\/\/github.com\/Aprataksh\/Minesweeper\" target=\"_blank\" rel=\"noreferrer noopener\" class=\"rank-math-link\">Github account<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will be going through the steps of creating our own terminal-based Minesweeper using Python Language. About the game Minesweeper is a single-player game in which the player has to clear a square grid containing mines and numbers. The player has to prevent himself from landing on a mine with the help [&hellip;]<\/p>\n","protected":false},"author":11,"featured_media":6507,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-6491","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/6491","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/11"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=6491"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/6491\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/6507"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=6491"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=6491"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=6491"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}