Python implements text version minesweeper

The examples in this article share the specific code of python to achieve the text version of minesweeper for your reference. The specific content is as follows

python version: 2.7

Game running diagram:

The code has been commented very clearly, no nonsense, just go to the code:
2 Algorithms: 1. Random number generation algorithm, 2. Breadth first

# coding:utf-8import sys
import random
import Queue
# Save data format of different game difficulty: difficulty: (row, line, mine)
DIFFICUL_DATA ={1:(8,8,5),2:(10,10,20),3:(15,15,100)}
# Save some data of different game results
RESULT_DATA ={0:"Statistics",1:"Game victory",2:"game over"}classSweep_Mine(object):
def __init__(self):"""
Function: instantiate function
"""
self.row =0
self.line =0
self.mine_num =0
self.map_list =[]
self.clean_count =0
self.step_count =0
self.level =0
self.result =0  #Save game results, 0:Not over yet,1:Game victory,2:game over
self.queue = Queue.Queue()
def show_desc(self):"""
Function: print game description
"""
print "=============================="
print "|game instructions|"
print "|  |"
print "|  |"
print "| #For locations that have not been cleared of mines|"
print "| *For the location of the mine|"
print "|0 is blank area|"
print "| 1-8 is the number of surrounding mines|"
print "|  |" 
print "|  |" 
print "|Enter X/Y:Minesweeper position|" 
print "| X/Y input 99:Refresh map|"
print "| X/Y input 88:exit the game|"
print "|  |" 
print "==============================" 
print "------------------------------" 
def show_result(self):"""
Function: Print information display
parameter:
select 0 print statistics
1 Print game victory
2 Print game over
"""
print "\n============================"
print RESULT_DATA.get(self.result)  #From RESULT_Print result data in DATA
print "\n number of mines: %d steps:%d "%(self.mine_num,self.step_count)
print "Mine cleared: %d remaining mine pits:%d "%(self.clean_count,\
self.row*self.line - self.clean_count -self.mine_num)
print "============================" 
def init_data(self):"""
Function: difficulty selection, data initialization
"""
self.clean_count =0
self.step_count =0
self.row = DIFFICUL_DATA[self.level][0]   #Grade from the global variable_Get difficulty data
self.line = DIFFICUL_DATA[self.level][1]
self.mine_num = DIFFICUL_DATA[self.level][2]
self.map_list =[['#'for i inrange(self.row)]for i inrange(self.line)] #map_list fill'#'
random_list = random.sample(range(self.row*self.line),self.mine_num)  #Get mine_num random numbers
for i in random_list:
x = i%self.row    #Use random number pairs to take the remainder
y = i/self.row    #Use random number pairs to take the quotient
self.map_list[y][x]='*'   #Random location set mine
def set_level(self,lvl):"""
Function: Set game difficulty
parameter:
lvl is 123 different levels of difficulty
return:
True set level successfully
False Setting level failed
"""
if lvl ==1 or lvl ==2 or lvl ==3: 
self.level = lvl
self.init_data()return True
else:return False
def check_result(self):"""
Function: Determine whether the game is won
return: 
self.result
0 Not over
1 victory
2 failure
"""
if self.row*self.line-self.clean_count <= self.mine_num:
self.result =1return self.result
def bfs(self):"""
BFS breadth first search blank area
"""
queue_temp =[]
around =[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]while not self.queue.empty():
self.clean_count +=1 
mine =0
q_x=self.queue.get()
q_y=self.queue.get()for value in around:
line = q_y + value[0]
row = q_x + value[1]if line<0 or line =self.line or row<0 or row =self.row:continueif self.map_list[line][row]=='*':
mine +=1
elif self.map_list[line][row]=='#':
queue_temp.append([line,row])  #Temporarily save to queue_temp 
if mine   0: 
self.map_list[q_y][q_x]=str(mine)  #Mark the number of mines
queue_temp =[]   #Empty queue_temp 
else:
self.map_list[q_y][q_x]='0'  #Set as blank area'0'whilelen(queue_temp):   #Will queue_The value in temp is placed in the queue
temp = queue_temp.pop(0)
self.map_list[temp[0]][temp[1]]='0' #Prevent looking back
self.queue.put(temp[1])  #Add blank points to the queue
self.queue.put(temp[0])
def show_game(self,showmine=False):"""
Function: display minesweeper map
Parameters: the default showmine is False, normal display,Hidden mine location
showmine is True special display,Show the location of the mine on the map
"""
output_temp =[]  #Save output characters
num_temp =[]  #Save the serial number of the horizontal and vertical coordinates
len = self.row if self.row  = self.line else self.line #Save the long side of the row or line
for num inrange(len):if num <10:
num_temp.append(str(num)+' ')else:
num_temp.append(str(num)+' ')
output_temp.append(" X ")for x inrange(self.row):
output_temp.append(num_temp[x])
output_temp.append('\nY ')for x inrange(self.row):
output_temp.append('---')for y inrange(self.line):
output_temp.append('\n'+num_temp[y]+'| ')for x inrange(self.row):if self.map_list[y][x]=='*':if showmine == True:
output_temp.append('* ')else:
output_temp.append('# ')else:
output_temp.append(self.map_list[y][x]+' ')
print ''.join(output_temp)
def input_pos(self,y,x):"""
Function: input mine sweeping position
Parameters: input integer x,y
Indicates the location to be cleared,x is the abscissa,y is the ordinate
x/y =99, refresh the map
x/y =88, end the game
return:
True: successful mine sweeping
False: Minesweeping failed
"""
if x inrange(self.row) and y inrange(self.line):
self.step_count +=1  #Steps plus one
if self.map_list[y][x]=='*': #Stepped on a mine
self.result =2  #Failed to set game result
return True
elif self.map_list[y][x]=='#': #Successful
self.queue.put(x)
self.queue.put(y)
self.bfs()return True
else:return False
else:if x ==99 or y ==99: #Enter 99 to refresh the map
self.init_data()return True
elif x ==88 or y ==88: #Enter 88 and the game is over
self.result =2return True
else:return False
if __name__ =='__main__':
game =Sweep_Mine()
game.show_desc()  #Print game description
while True:  #Big loop input game difficulty
level =raw_input("Please select the difficulty of the game\n input: 1, 2, 3\n")if level.isdigit()!= True: #If the input is not a number
print("Invalid, please enter a number!")continueelse:
level =int(level)if game.set_level(level)== True: #Select difficulty successfully launched
breakelse:print("Difficulty selection failed!")while game.check_result()==0:  #The game is not over, keep looping input x/y
game.show_game() 
game.show_result()
x =raw_input("Input X:")
y =raw_input("Input Y:")if x.isdigit()!= True or y.isdigit()!= True: #If the input is not a number
print "Invalid, please enter a number!"continueelse:
x =int(x)
y =int(y)if game.input_pos(y,x):  #Enter the location of minesweeper
print "Minesweeping succeeded!"else:
print "Wrong input location!"
game.show_game(True)  #game over
game.show_result()
sys.exit(0)

More interesting classic mini game implementation topics, share with you:

C++ classic games summary

Python classic games summary

python tetris game collection

JavaScript classic games are constantly playing

Summary of classic java games

JavaScript classic games summary

The above is the whole content of this article, I hope it will be helpful to everyone's study.

Recommended Posts

Python implements text version minesweeper
Python implements minesweeper game
Python implements minesweeper games
Python implements AI automatic version greedy snake
Ubuntu18.04 switch Python version
Python implements Super Mario
Python implements tic-tac-toe game
Python implements text version minesweeper
How to filter numbers in python
Python implements tic-tac-toe game
Ubuntu16.04 switch python version
Python implements man-machine gobang
Python implements Tetris game
Python implements image stitching
Python implements scanning tools
python tic-tac-toe-text version (part 2)
PyCharm set Python version
Python implements threshold regression
python Tic-Tac-Toe-text version (on)
Python implements electronic dictionary
Python implements guessing game
Python implements WeChat airplane game
Python implements word guessing game
Python implements a guessing game
Python implements parking management system
Python implements digital bomb game
Python implements TCP file transfer
Python numpy implements rolling case
OpenCV Python implements puzzle games
Python implements password strength verification
Python implements car management system
Python implements code block folding
Python implements panoramic image stitching
Python implements SMTP mail sending
Python implements multi-dimensional array sorting
How Python implements FTP function
Python implements mean-shift clustering algorithm
Python implements gradient descent method
Python version of OpenCV installation
Python implements image stitching function
Python implements the brick-and-mortar game
Python implements student performance evaluation system
Python simply implements the snake game
Python3 implements the singleton design pattern
Python implements exchange rate conversion operations
Python implements ten classic sorting algorithms
Python implements 126 mailboxes to send mail
Python implements AI face change function
Python implements the steepest descent method
Python implements the actual banking system
Python implements digital bomb game program
Install TensorFlow (python2.7 version) on Ubuntu
Python implements ftp file transfer function
Python implements username and password verification
How Python implements the timer function
Python implements the aircraft war project
Python implements horizontal stitching of pictures
Python implements GIF graph upside down