Python 代码在 2.7 中有效但在 3.5 中无效

Python code works in 2.7 but not in 3.5

我的课程是在 Python 中创建 Tic Tac Toe,我的导师帮助我让它在 2.7 中运行,但它需要在 3.5 中运行。

首先在 2.7 中,下面的代码打印一个 3x3 列表,但是在 3.5 中它只是向下打印列表而不是 3x3。我的导师说可以把 end = ' ' 放在最后,但这也行不通。

def printBoard( board ):
    counter = 0   
    for y in range(3):    
        for x in range(3):    
            print (board[counter]),    
            counter += 1    
        print    
    print

第二个问题在2.7允许我继续输入数字直到棋盘上填满X或O,在3.5只允许输入一次然后程序结束?

value = input("input number between 1 and 9")    
value = int(value)        
if value == 1:    
    alist[0] = player1    
    printBoard( alist )    
    value = input("input number between 1 and 9")    
if value == 2:    
    alist[1] = player1    
    printBoard( alist )    
    value = input("input number between 1 and 9")

等等

  1. print 从 Python 中的 statement to a function 更改为 3.x。要打印不带换行符的语句,您需要传递 end=' ' 参数(如果将 from __future__ import print_function 放在 from __future__ import print_function 的开头,则可以将 print 用作 Python 2.7 中的函数代码):

    print(board[counter], end=' ')
    
  2. input returns Python 3.x 中的一个字符串。 (不评估输入字符串)。您需要在每个使用 input:

    的地方将该值转换为 int
    value = input("input number between 1 and 9")
    value = int(value)
    

    或者,不是将输入与整数文字 12 进行比较,而是将输入字符串与字符串:'1''2' 进行比较,而不将字符串转换为整数。 (但这需要你在 Python 2.7 中使用 raw_input 而不是 input

  3. print应该叫:print()。否则,什么都不打印。

我假设 board 类似于 [['*', '*', '*'], ['*', '*', '*'], ['*', '*', '*']]。这意味着您可以轻松地通过单个 print() 调用来打印它。

print(*(''.join(row) for row in board), sep='\n')

这会将每一行连接成一个新字符串,将每一行生成为生成器的一部分。此生成器用 * 解包并发送到 print(),其中每行由换行符分隔。

对于你的第二个问题,问题很简单:你为第一个value投了int(),但没有为后续的投。然而,这是你应该用循环做的事情。它会完全防止这种错误。如果您发现自己使用 Ctrl+V 编写了大量代码,那么您做错了什么。如果每个块略有不同,有一个递增的数字,你可以用像 for i in range(n): 这样的东西来做到这一点,它允许你在每次迭代中用一个递增的数字执行相同的代码。

但是,我推荐一个简单的 while 循环来检查游戏是否完成:

while True:
    move = request_move()
    do_move('X', move)
    if game_complete():
        break
    request_move()
    do_move('O', move)
    if game_complete():
        break

然后您将编写适当的函数来请求移动坐标、将移动输入棋盘并检查游戏是否完成。