我试图创建某种扫雷地图创建者,但有一个困难的时间与它。脚本应该得到地图上的许多列和行,然后取炸弹的数量和它们的位置。
在创建的地图中,炸弹应该显示为*,其他单元应该包括它们的邻居中的炸弹数量(对角线包括在内)。
(例如):
* 1
1 1或
* 3 3 *
* 3 * *
1 2 2 2 我的代码:
#takes the number of colmuns and lines from user
xy=input()
xy=xy.split(" ")
m=int(xy[0])
n=int(xy[1])
#takes the number of the bombs
number=int(input())
bomb=[""]*number
matrix = [[0 for x in range(m)] for y in range(n)]
#take position of the bombs
for i in range(number):
bomb[i]=input()
for i in range(number):
o=bomb[i].split(" ")
x=int(o[0])-1
y=int(o[1])-1
#puts * in matrix as bombs
matrix[y][x]="*"
#checks the neighbor cells of the bomb
for j in range(-1,2):
for k in range(-1,2):
#shouldnt check the bombs cell
if j!=0 or k!=0:
#ignores some type and index errors
try:
matrix[y+j][x+k]+=1
except:
pass
#turn the matrix to desired format
for i in range(m):
string=""
for j in range(n):
string+=str(matrix[j][i])+" "
print(string)输入如下:
2 2 #columns and lines
1 #number of bombs
1 1 #postion of bombs all in separate lines它应返回:
* 1
1 1但它会返回:
* 2
2 4我不知道这里出了什么问题
发布于 2020-12-15 19:46:35
正如人们在评论中指出的那样,你不能正确地处理负面消息。举个例子:
print(["hi", "hello"][-1])输出hello。这是因为-1将是最后一个元素。和-2将是第二个最后,以此类推,这意味着它处理这些完全好,没有错误。这意味着您应该检查该数字是否大于-1,方法是
if j!=0 or k!=0:
#ignores numbers less than 0
if y + j > -1 and x + k > -1:
matrix[y+j][x+k]+=1https://stackoverflow.com/questions/65312281
复制相似问题