python to write minesweeper example code sharing

  • 2020-10-23 20:09:32
  • OfStack

Minesweeper is a classic WIN game. We teach you to write the game in python. Here are all the examples:


#!/usr/bin/python
#coding:utf-8

#python  Write the minesweeper game 


import sys
import random

class MineSweeping():
  # Main minesweeping procedure 
  def __init__(self,row = 8 ,line= 8,mineNum = 15):
    self.row = row
    self.line = line
    self.score = 0 # score 
    self.mineNum = mineNum
    self.xy_list = [[0 for i in range(self.line)] for i in range(self.row)]

  def initData(self):
    #  Initialize the status value 
    #  The game starts with zero status ( Reset the status value again )
    self.xy_list = [[0 for i in range(self.line)] for i in range(self.row)]
    #  Set the number of mines 
    maxMine = self.mineNum
    while maxMine > 0 :
      num_x = random.randint(0,self.row-1)
      num_y = random.randint(0,self.line-1)
      if self.xy_list[num_x][num_y] == 0:
        self.xy_list[num_x][num_y] = 1
        maxMine -= 1

  # To obtain x coordinates 
  def get_pos(self,str_pos):
    # To obtain x coordinates 
    while 1:
      try:
        num_x = raw_input(str_pos)
        if int(num_x) in range(self.line) and num_x :
          break
        else:
          print u' Input invalid value '
      except:
        pass
    return int(num_x)

  # For mine 
  def mine_clear(self,x,y):
    #  Sets the number of sweeps shown 
    #  Setting up the digital 
    # 0  Represents the sweep of thunder 
    # 1  Said class 
    # 2  Represents the swept class 

    # Gets the number of coordinates 
    pos = self.xy_list[x][y]
    if pos == 0 :
      self.xy_list[x][y] = 2
      return 0
    elif pos == 2 :
      return 2
    else:
      return 1

  # Interface display 
  def mineFace(self,state):
    # Display the contents of the interface 
    # Set the game's state 
    #1  Represents the state of the run 
    #2  Represents the state of the output 
    #3  Represents the state at the end of the game 
    #4  It means that the game has won outright 
    if state == 1:
      print '+=================+'
      print '   Game start  '
      print '+=================+'
      tt = ' #'
      print '**************************'
      for i in range(self.line):
        str_t = ''
        for t in xrange(self.row):
          str_t += tt
        print "|%s|"%(str_t,)
      print '**************************'
      print 'Please input values of x,y(0-7):'
    # Refresh the user interface 
    if state == 2:
      tt = ' #'
      print '**************************'
      for i in range(self.line):
        str_t = ''
        for t in xrange(self.row):
          if self.xy_list[i][t] == 2:
            str_t += str(self.xy_list[i][t]).rjust(2)
          else:
            str_t += tt
        print "|%s|"%(str_t,)
      print '**************************'
    if state == 3:
      print '**************************'
      for i in range(self.line):
        str_t = ''
        for t in xrange(self.row):
          if int(self.xy_list[i][t]) != 1:
            str_t += ' 2'
          else:
            str_t += ' *'
        print "|%s|"%(str_t,)
      print '**************************'

    if state == 4:
      tt = ' #'
      print '**************************'
      for i in range(self.line):
        str_t = ''
        for t in xrange(self.row):
          if self.xy_list[i][t] == 2:
            str_t += str(self.xy_list[i][t]).rjust(2)
          else:
            str_t += ' @'
        print "|%s|"%(str_t,)
      print '**************************'


  def MainLoop(self):
    # Create the game's main loop 

    # Create the interface to run 
    self.mineFace(1)
    self.score = 0
    self.initData()
    #print self.xy_list


    #  Go into the main loop 
    while 1:
      # Gets the position of the coordinates 
      x = self.get_pos(' X = ')
      y = self.get_pos(' Y = ')
      num = self.mine_clear(x,y)
      # The judgment is no more than a resounding victory 
      win = True
      for i in self.xy_list:
        if 0 in i:
          win = False
          break
      if win:
        num = 4

      # Perform a function to refresh the interface 
      if num == 0:
        self.mineFace(2)
        self.score += 10
      elif num == 2:
        print u' This position has already been arranged , Confirmed that there was no mine '
      elif num == 1:
        print '+=================+'
        print '   Game over  '
        print '+=================+'
        print u' score  : ', self.score
        self.mineFace(3)
        #  Should I move on 1 other 
        next = raw_input(u' That's enough to go on 1 Bureau of :Y or N ')
        if next.upper().startswith('Y'):
          print u' Under the 1 set '
          self.nextGame()
        else:
          print '>>> Game exit'
          break
      else:
        self.score += 10
        print u' Congratulations on your complete victory '
        print u' score  : ', self.score
        self.mineFace(4)
        next = raw_input(u' That's enough to go on 1 Bureau of :Y or N ')
        if next.upper().startswith('Y'):
          print u' Under the 1 set '
          self.nextGame()
        else:
          print '>>> Game exit'
          break

  #  Under the 1 Bureau initializes the message 
  def nextGame(self):
    self.mineFace(1)
    self.score = 0
    self.initData()


if __name__ == '__main__':
  mi = MineSweeping(10,10,20)
  mi.MainLoop()
  sys.exit()


If you have any questions during the test, please discuss them in the comments section below. Thank you for your support for this site.


Related articles: