我想制作一个tic tac toe游戏,我正在制作它,当用户输入数字1 - 9时,它在网格上的相应空间上创建一个X.这是函数:
A
等等,网格显示X在正确的位置。但接下来的转折来了。我希望让他们输入一个新号码,但保留旧X的位置。我在想:有没有办法用不同的参数将该功能与自身结合起来并让它们在网格上放置两个X? 所以,我的问题是,是否有这个功能,如果没有,我将如何做到这一点。
答案 0 :(得分:2)
编程时,如果你发现自己一遍又一遍地复制粘贴相同的代码,那就错了。你应该从一开始就重新思考这件事。怎么样?
board = [' '] * 9 # the 9 cells, empty at first
def show(board):
for row in range(3):
print '|',
for col in range(3):
print board[row*3 + col], '|',
print # newline
def move(inp):
board[inp-1] = 'X' # user input is 1-based, Python is 0-based
show(board)
答案 1 :(得分:2)
你可以这样做:
def make_square(inp):
square = " {0} |{1}\t|{2}\n_____________\n {3} | {4}\t|{5}\n_____________\n {6} |{7}\t|{8}" # set {} brackets for 'X' format
inp += -1 # rest because need take from 0 as the brackts indice
for x in range(9): # range max of 'X'
if x != inp:
square = square.replace('{}'.format(x),' ') # delete brackets without the number select by the user
# {{ {0} }} explication http://stackoverflow.com/a/5466478/4941927
square = square.replace('{{{0}}}'.format(inp),'{0}') # convert current {number} into {0} for format
square = square.format('X') # formatting brackets for the 'X'
print square
make_square(2)
如果您需要帮助,我很乐意提供帮助 问候!