我正在为正在执行的Battleships项目编写这段代码,我相信在将这些部分分配给子例程中的板子时遇到了逻辑错误。
“和(c ==(x + 1)或c ==(x-1))和(b ==(y + 1)或b ==(y-1))”
#FUNCTION - PLACE TILES
grid = [[" "," "," "],[" "," "," "],[" "," "," "]]
mrk = "X"
cruiser = 2
while True:
try:
x,y = input("which tile would you like to place your ship on?").split(",")
x = int(x)
y = int(y)
if x in range(0,3) and y in range(0,3):
grid[x][y] = mrk
cruiser -= 1
else:
x,y = input("which tile would you like to place your ship on?").split(",")
break
except ValueError:
x,y = input("INVALID CHARACTER\n\nwhich tile would you like to place your ship on?").split(",")
while cruiser < 2 and cruiser > 0:
while True:
try:
c,b = input("which tile would you like to place your ship on?").split(",")
c = int(c)
b = int(b)
print(c,b,x,y)
if c in range(0,3) and b in range(0,3) and (c == (x+1) or c == (x-1)) and (b == (y+1) or b == (y-1)) :
grid[c][b] = mrk
cruiser -= 1
else:
c,b = input("INVALID POSITION\n\nwhich tile would you like to place your ship on?").split(",")
break
except ValueError:
c,b = input("INVALID CHARACTER\n\nwhich tile would you like to place your ship on?").split(",")
print (grid[0][0]," | ",grid[0][1]," | ",grid[0][2])
print (grid[1][0]," | ",grid[1][1]," | ",grid[1][2])
print (grid[2][0]," | ",grid[2][1]," | ",grid[2][2])
由于它使用try和except,因此不会产生任何错误消息-但是,确实出现了我的代码中所示的INVALID POSITION。它应该接受该值,然后检查它是否仅与另一个点水平或垂直对齐,然后绘制它。
编辑:HTML / CSS代码段让您直观地看到我正在尝试做什么,谢谢
.grid-container {
display: grid;
grid-template: auto / auto auto auto;
grid-gap: 5px;
background-color: #000000;
padding: 0px;
}
.grid-container>div {
background-color: rgba(255, 255, 255, 0.8);
text-align: center;
padding: 20px 0;
font-size: 30px;
}
<!DOCTYPE html>
<html>
<body>
<p1> If the top right X was the first value plotted, valid positions for X would be everything marked X1, and invalid positions would be marked Y </p1>
<div class="grid-container">
<div class="item1">X</div>
<div class="item2">X1</div>
<div class="item3">X1</div>
<div class="item4">X1</div>
<div class="item5">Y</div>
<div class="item6">Y</div>
<div class="item7">X1</div>
<div class="item8">Y</div>
<div class="item9">Y</div>
</div>
</body>
</html>
答案 0 :(得分:0)
不确定我是否理解您想要做什么,但是我将替换掉
and (c == (x+1) or c == (x-1)) and (b == (y+1) or b == (y-1))
通过
and c != x and b != y
在我看来,您只想确认c
和b
与x
和y
不在同一位置。
更新:
有了新的信息,您实际上希望将每个新标记放置在与前一个标记相邻的位置,而不是对角线,那么您确实应该存储最后一个标记的位置(例如prev_x
,prev_y
)并在每个有效输入处进行更新,因此您可以将其与下一个输入的新值进行比较,依此类推。
除此之外,为防止将标记放置在对角线上,我认为没有魔术公式。您需要检查c
和b
是否不在对角线上。
[...]
# avoid diagonals in relation to the previous marker
and not (c == prev_x - 1 and b == prev_y - 1)
and not (c == prev_x - 1 and b == prev_y + 1)
and not (c == prev_x + 1 and b == prev_y - 1)
and not (c == prev_x + 1 and b == prev_y + 1)
[...]