Python Minesweeper
The following is useful as part of a program to play Minesweeper. Suppose you have a 5 X 5 list that consists of zeros and M’s. Write a program that creates a new 5 5 list that hasM’s in the same place, but the zeroes are replaced by counts of how many M’s are in adjacent cells (adjacent either horizontally, vertically, or diagonally). An example is shown below. [Hint: short-circuiting may be helpful for avoiding index-out-of-range errors.]
L =
[[0, 'M', 0, 'M', 0],
[0, 0, 'M', 0, 0],
[0, 0, 0, 0, 0],
['M', 'M', 0, 0, 0],
[0, 0, 0, 'M', 0]]
brojac = 0
for i in range(len(L)):
for j in range(len(L)):
print(L[i][j], end=' ')
print()
print()
for i in range(len(L)):
for j in range(len(L)):
brojac = 0
if L[i][j] == 0:
if i > 0 and L[i-1][j-1] == 'M':
brojac += 1;
if L[i-1][j] == 'M':
brojac +=1;
if 0 <= j <4 and i > 0 and L[i-1][j + 1] == 'M':
brojac += 1;
if L[i][j-1] == 'M':
brojac +=1;
if 0 <= j <4 and L[i][j+1] == 'M':
brojac +=1;
if 0 <= i <4 and L[i+1][j-1] == 'M':
brojac +=1;
if 0 <= i <4 and L[i+1][j] == 'M':
brojac +=1;
if 0 <= i <4 and 0 <= j < 4 and L[i+1][j+1] == 'M':
brojac +=1;
L[i][j] = brojac
for i in range(len(L)):
for j in range(len(L)):
print(L[i][j], end=' ')
print()
0 M 0 M 0
0 0 M 0 0
0 0 0 0 0
M M 0 0 0
0 0 0 M 0
1 M 3 M 1
1 2 M 2 1
2 3 2 1 0
M M 2 1 1
2 2 2 M 1
[0, 0, 'M', 0, 0],
[0, 0, 0, 0, 0],
['M', 'M', 0, 0, 0],
[0, 0, 0, 'M', 0]]
brojac = 0
for i in range(len(L)):
for j in range(len(L)):
print(L[i][j], end=' ')
print()
print()
for i in range(len(L)):
for j in range(len(L)):
brojac = 0
if L[i][j] == 0:
if i > 0 and L[i-1][j-1] == 'M':
brojac += 1;
if L[i-1][j] == 'M':
brojac +=1;
if 0 <= j <4 and i > 0 and L[i-1][j + 1] == 'M':
brojac += 1;
if L[i][j-1] == 'M':
brojac +=1;
if 0 <= j <4 and L[i][j+1] == 'M':
brojac +=1;
if 0 <= i <4 and L[i+1][j-1] == 'M':
brojac +=1;
if 0 <= i <4 and L[i+1][j] == 'M':
brojac +=1;
if 0 <= i <4 and 0 <= j < 4 and L[i+1][j+1] == 'M':
brojac +=1;
L[i][j] = brojac
for i in range(len(L)):
for j in range(len(L)):
print(L[i][j], end=' ')
print()
0 M 0 M 0
0 0 M 0 0
0 0 0 0 0
M M 0 0 0
0 0 0 M 0
1 M 3 M 1
1 2 M 2 1
2 3 2 1 0
M M 2 1 1
2 2 2 M 1
Коментари
Постави коментар