資源描述:
《python實現(xiàn)的掃雷游戲源碼》由會員上傳分享,免費在線閱讀,更多相關內(nèi)容在應用文檔-天天文庫。
1、樣例輸出:mine=13length=10OriginMatrix=[]#保存原始地雷矩陣NumberMatrix=[]#保存計算后的數(shù)字矩陣StateMatrix=[]#保存矩陣的顯示狀態(tài)#生成地雷矩陣fromrandomimportrandintforiinrange(0,length):temp=[]forjinrange(0,length):temp.append('.');OriginMatrix.append(temp)foriinrange(0,mine):x=randint(0,9)y=randint(0,9)Orig
2、inMatrix[x][y]='*'delrandint#randint不再使用#生成對應的數(shù)字矩陣#函數(shù)定義,該函數(shù)返回某點相鄰地雷數(shù)(包括自身)defnumber(x,y):counter=0foriin[0,1,-1]:forjin[0,1,-1]:ifx+i<0orx+i>=length:continueelify+j<0ory+j>=length:continueelifOriginMatrix[x+i][y+j]!='*':continueelse:counter+=1returncounter#計算forxinrange
3、(0,length):temp=[]foryinrange(0,length):temp.append(number(x,y))NumberMatrix.append(temp)#剔除地雷點(將其相鄰地雷數(shù)設為9,表示該點為地雷)foriinrange(0,length):forjinrange(0,length):ifOriginMatrix[i][j]=='*':NumberMatrix[i][j]=9delOriginMatrix#OriginMatrix不再使用#定義一些用到的函數(shù)#顯示函數(shù),用于顯示矩陣fromosimpor
4、tsystemdefdisplay(verdict):#verdict參數(shù)用于在挖中地雷時顯示地雷system('cls')temp=''foriinrange(0,length):temp+=(str(i)+'')print(temp)foriinrange(0,length):temp=str(i)+''forjinrange(0,length):ifNumberMatrix[i][j]==9andnotverdict:temp+='*'continueifStateMatrix[i][j]:ifNumberMatrix[i][j
5、]==0:temp+=''else:temp+=(str(NumberMatrix[i][j])+'')else:temp+='■'print(temp)#剔除函數(shù),用于剔除顯而易見的不為地雷的位置CheckSet=set()defopenWhile(x,y):if(x,y)inCheckSet:returnelifNumberMatrix[x][y]>1:returnelse:StateMatrix[x][y]=TrueCheckSet.add((x,y))#與0相鄰的都顯示ifNumberMatrix[x][y]==0:forii
6、n[-1,0,1]:forjin[-1,0,1]:ifx+i>=0andx+i=0andy+j=0:openWhile(x-1,y)ify-1>=0:openWhile(x,y-1)ifx+17、emp.append(e.copy())foriinrange(0,length):forjinrange(0,length):ifNumberMatrix[i][j]==9:temp[i][j]=Trueforiinrange(0,length):forjinrange(0,length):ifnottemp[i][j]:returnTruereturnFalse#下面開始游戲#初始化StateMatrixforiinrange(0,length):temp=[]forjinrange(0,length):temp.append(F
8、alse)StateMatrix.append(temp)#Mainpartofthegamewhileestimate():display(True)x=int(input('Inputrownumber:'))y=i