Don't like ads? PRO users don't see any ads ;-)
Guest

Minesweeper in Python 1.1

By: a guest on Dec 24th, 2011  |  syntax: Python  |  size: 4.76 KB  |  hits: 561  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import string
  2. import random
  3.  
  4. def setupgrid(gridsize,start,numberofmines):
  5.     grid = [['0' for i in range(gridsize)] for i in range(gridsize)]
  6.     mines = generatemines(grid,start,numberofmines)
  7.     getnumbers(grid)
  8.     return (grid,mines)
  9.  
  10. def showgrid(grid):
  11.     gridsize = len(grid)
  12.     horizontal = '   '+4*gridsize*'-'+'-'
  13.     # Print top column letters
  14.     toplabel = '     '
  15.     for i in string.ascii_lowercase[:gridsize]:
  16.         toplabel = toplabel+i+'   '
  17.     print toplabel+'\n'+horizontal
  18.     # Print left row numbers
  19.     for idx,i in enumerate(grid):
  20.         row = '{0:2} |'.format(idx+1)
  21.         for j in i:
  22.             row = row+' '+j+' |'
  23.         print row+'\n'+horizontal
  24.     print ''
  25.  
  26. def getrandomcell(grid):
  27.     gridsize = len(grid)
  28.     a = random.randint(0,gridsize-1)
  29.     b = random.randint(0,gridsize-1)
  30.     return (a,b)
  31.  
  32. def getneighbors(grid,rowno,colno):
  33.     gridsize = len(grid)
  34.     row = grid[rowno]
  35.     column = grid[rowno][colno]
  36.  
  37.     neighbors = []
  38.  
  39.     for i in range(-1,2):
  40.         for j in range(-1,2):
  41.             if i == 0 and j == 0: continue
  42.             elif -1<rowno+i<gridsize and -1<colno+j<gridsize:
  43.                 neighbors.append((rowno+i,colno+j))
  44.     return neighbors
  45.  
  46. # Generate mines
  47. def generatemines(grid,start,numberofmines):
  48.     gridsize = len(grid)
  49.     mines = []
  50.     for i in range(numberofmines):
  51.         cell = getrandomcell(grid)
  52.         while cell==(start[0],start[1]) or cell in mines:
  53.             cell = getrandomcell(grid)
  54.         mines.append(cell)
  55.  
  56.     for i,j in mines: grid[i][j] = 'X'
  57.     return mines
  58.  
  59. def getnumbers(grid):
  60.     gridsize = len(grid)
  61.     for rowno,row in enumerate(grid):
  62.         for colno,col in enumerate(row):
  63.             if col!='X':
  64.                 # Gets the values of the neighbors
  65.                 values = [grid[r][c] for r,c in getneighbors(grid,rowno,colno)]
  66.  
  67.                 # Counts how many are mines
  68.                 grid[rowno][colno] = str(values.count('X'))
  69.  
  70. def showcells(grid,currgrid,rowno,colno):
  71.     # Exit function if the cell was already shown
  72.     if currgrid[rowno][colno]!=' ':
  73.         return
  74.  
  75.     # Show current cell
  76.     currgrid[rowno][colno] = grid[rowno][colno]
  77.  
  78.     # Get the neighbors if the cell is empty
  79.     if grid[rowno][colno] == '0':
  80.         for r,c in getneighbors(grid,rowno,colno):
  81.             # Repeat function for each neighbor that doesn't have a flag
  82.             if currgrid[r][c] != 'F':
  83.                 showcells(grid,currgrid,r,c)
  84.  
  85. def playagain():
  86.     choice = raw_input('Play again? (y/n): ')
  87.     return choice.lower() == 'y'
  88.  
  89. def playgame():
  90.     numberofmines = 10
  91.     gridsize = 9
  92.  
  93.     currgrid = [[' ' for i in range(gridsize)] for i in range(gridsize)]
  94.     showgrid(currgrid)
  95.     grid = []
  96.     flags = []
  97.     helpmessage = "Type the column followed by the row (eg. a5).\nTo put or remove a flag, add 'f' to the cell (eg. a5f)\n"
  98.     print helpmessage
  99.  
  100.     while True:
  101.         while True:
  102.             lastcell = str(raw_input('Enter the cell ({} mines left): '.format(numberofmines-len(flags))))
  103.             print '\n\n'
  104.             flag = False
  105.             try:
  106.                 if lastcell[2] == 'f': flag = True
  107.             except IndexError: pass
  108.  
  109.             try:
  110.                 if lastcell == 'help':
  111.                     print helpmessage
  112.                 else:
  113.                     lastcell = (int(lastcell[1])-1,string.ascii_lowercase.index(lastcell[0]))
  114.                     break
  115.             except (IndexError,ValueError):
  116.                 showgrid(currgrid)
  117.                 print "Invalid cell.",helpmessage
  118.  
  119.         if len(grid)==0:
  120.             grid,mines = setupgrid(gridsize,lastcell,numberofmines)
  121.         rowno,colno = lastcell
  122.  
  123.         if flag:
  124.             # Add a flag if the cell is empty
  125.             if currgrid[rowno][colno]==' ':
  126.                 currgrid[rowno][colno] = 'F'
  127.                 flags.append((rowno,colno))
  128.             # Remove the flag if there is one
  129.             elif currgrid[rowno][colno]=='F':
  130.                 currgrid[rowno][colno] = ' '
  131.                 flags.remove((rowno,colno))
  132.             else: print 'Cannot put a flag there'
  133.  
  134.         else:
  135.             # If there is a flag there, show a message
  136.             if (rowno,colno) in flags:
  137.                 print 'There is a flag there'
  138.             else:
  139.                 if grid[rowno][colno] == 'X':
  140.                     print 'Game Over\n'
  141.                     showgrid(grid)
  142.                     if playagain(): playgame()
  143.                     else: exit()
  144.                 else:
  145.                     showcells(grid,currgrid,rowno,colno)
  146.  
  147.         showgrid(currgrid)
  148.  
  149.         if set(flags)==set(mines):
  150.             print 'You Win'
  151.             if playagain(): playgame()
  152.             else: exit()
  153.  
  154. playgame()