如何在保持运行的同时打破我的while循环?

时间:2018-05-19 18:40:46

标签: python

我已经制作了一个Tic-Tac-Toe游戏的程序,我想这样做,当你输入一次瓷砖时,它的占位符已经填满,但是当你再次进入瓷砖时它会停止while循环。我该怎么办?这是我的代码:

userInput = input("Chose a tile: 1, 2, 3, 4, 5, 6, 7, 8, 9.")
tile1 = 0
tile2 = 0
tile3 = 0
tile4 = 0
tile5 = 0
tile6 = 0
tile7 = 0
tile8 = 0
tile9 = 0
Stanford = 666
gameBoardMatrix = [
    ['1','2','3'], 
    ['4','5','6'],
    ['7','8','9']
]
while Stanford == 666:
  if userInput == '1':
    print ("You chose" + " " + gameBoardMatrix [0][0])
    tile1 = tile1 + 0.5
  if userInput == '2':
    print ("You chose" + " " + gameBoardMatrix [0][1])
  if userInput == '3':
    print ("You chose" + " " + gameBoardMatrix [0][2])
  if userInput == '4':
    print ("You chose" + " " + gameBoardMatrix [1][0])
  if userInput == '5':
    print ("You chose" + " " + gameBoardMatrix [1][1])
  if userInput == '6':
    print ("You chose" + " " + gameBoardMatrix [1][2])
  if userInput == '7':
    print ("You chose" + " " + gameBoardMatrix [2][0])
  if userInput == '8':
    print ("You chose" + " " + gameBoardMatrix [2][1])
  if userInput == '9':
    print ("You chose" + " " + gameBoardMatrix [2][2])  
  if tile1 == 1:
    print("Oh my, you seem to have broken the laws of physics. THE GAME IS ENDING! THE WORLD IS BROKEN!")
    break

2 个答案:

答案 0 :(得分:0)

您希望将电路板的占用状态存储在类似于gameBoardMatrix的变量中,例如is_filled_matrix

is_filled_matrix = [
    [False, False, False],
    [False, False, False],
    [False, False, False]
]

当用户选择一个单元格时,您可以更新is_filled_matrix以反映更改:

if user_input == '1':
    is_filled_matrix[0][0] = True

稍后,如果用户访问已填充的此单元格,您可以通过查看is_filled_matrix来检查其占用情况。这可以通过修改代码来实现,如下所示:

if user_input == '1':
    if is_full_matrix[0][0]:
        # The first cell has already been visited, we break
        break

    # The first cell has not been visited, we continue to play
# ...

答案 1 :(得分:0)

根据我对你的问题的理解,你想在有人选择9个瓷砖中的任何一个时,立即退出while循环。
为此,您需要散列位置(平铺)和操作(单击) 您可以使用列表或字典来完成工作。

  

使用列表:

lst = [False] * 9
while True:
    tile = int(raw_input())
    if lst[tile]:
        break
    lst[tile] = True
  

使用字典:

d = {}
while True:
    tile = int(raw_input())
    if d.get(tile, False):
        break
    d[tile] = True