Python 嵌套 while 循环问题

Python nested while loop issues

我对编码比较陌生,我正在做一个项目,我制作一个类似于战舰的游戏,例如2 个玩家将 10 艘船放在 'board' 上,我为每个玩家制作了一个二维数组,其中 0 = 没有船,1 = 船。我这样做是为了让第一个玩家必须从 0-7 输入每艘船的 x 和 y 值,如果他们不从 0-7 输入它,它就在一个 while 循环中,所以它一直要求他们输入一个值0-7。我还想这样做,如果一组坐标上已经有一艘船,那么它会要求玩家输入一组新的坐标。但是,我在使用嵌套 while 循环时遇到了问题。

问题:

当我运行输入两个相同的坐标时,它会重复“你已经在这里放置了一个坦克。请输入另一组坐标。”。我认为当它 运行 通过外部循环时,它也可能跳过内部 while 循环?

p1Board = [[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0]]
flag3 = True
flag4 = True
var1 = True

#Player 1 Tank 2 
while var1 == True:
  while flag3 == True:
    p1XCoordTank2 = int(input("\nOn which x-coordinate would you like to place your second tank? "))
    flag3 = False
    if p1XCoordTank2 < 0 or p1XCoordTank2 > 7:
      print("Please choose an x-coordinate that is in the range 0-7. ")
      flag3 = True
  while flag4 == True:
    p1YCoordTank2 = int(input("On which y-coordinate would you like to place your second tank? "))
    flag4 = False
    if p1YCoordTank2 < 0 or p1YCoordTank2 > 7:
      print("Please choose an y-coordinate that is in the range 0-7. ")
      flag4 = True
  if p1Board[p1XCoordTank2][p1YCoordTank2] == 1:
    print("You already have a tank placed here. Please input another set of coordinates. ")
    var1 = True

不确定如何修复它。请帮帮我。

我无法重现您的错误信息:

You already have a tank placed here. Please input another set of coordinates.

在输入相同坐标时打印(f.e。p1XCoordTank2 = 0,p1YCoordTank2 = 0)。

但是,要阻止您从 运行 开始循环,您必须在某处将 var1 设置为 False:

flag3 = True
flag4 = True
var1 = True

#Player 1 Tank 2 
while var1 == True:
  while flag3 == True:
    p1XCoordTank2 = int(input("\nOn which x-coordinate would you like to place your second tank? "))
    flag3 = False
    if p1XCoordTank2 < 0 or p1XCoordTank2 > 7:
      print("Please choose an x-coordinate that is in the range 0-7. ")
      flag3 = True
  while flag4 == True:
    p1YCoordTank2 = int(input("On which y-coordinate would you like to place your second tank? "))
    flag4 = False
    if p1YCoordTank2 < 0 or p1YCoordTank2 > 7:
      print("Please choose an y-coordinate that is in the range 0-7. ")
      flag4 = True
  if p1Board[p1XCoordTank2][p1YCoordTank2] == 1:
    print("You already have a tank placed here. Please input another set of coordinates. ")
    var1 = True
  else:
    p1Board[p1XCoordTank2][p1YCoordTank2] = 1 #place the tank
    var1 = False #stop the while loop