我已经为井字游戏编写了代码,并且效果很好。但是,我不知道它是否有效。关于如何优化它有帮助吗?
def restart():
num=[0 for i in range(9)]
board=[" " for i in range(9)]
a=2
start(board,a,num)
def wincheck(t):
for i in range(8):
if t[win[i][0]]==t[win[i][1]] and t[win[i][0]]==t[win[i][2]] and
t[win[i][1]]==t[win[i][2]] and t[win[i][0]]!=" ":
if t[win[i][0]]=="X":
print("Player 1 wins")
else:
print("Player 2 wins")
playa = input("Do you want to play again? Y/N")
if playa.lower() == "y":
restart()
else:
exit(0)
def display_board(t,a,num):
print( " "*3+'|'+" "*3+'|'+" "*3)
print("{0:^3}|{1:^3}|{2:^3}".format(t[6],t[7],t[8]))
print( " "*3+'|'+" "*3+'|'+" "*3)
print("-"*11)
print( " "*3+'|'+" "*3+'|'+" "*3)
print("{0:^3}|{1:^3}|{2:^3}".format(t[3],t[4],t[5]))
print( " "*3+'|'+" "*3+'|'+" "*3)
print("-"*11)
print( " "*3+'|'+" "*3+'|'+" "*3)
print("{0:^3}|{1:^3}|{2:^3}".format(t[0],t[1],t[2]))
print( " "*3+'|'+" "*3+'|'+" "*3)
wincheck(t)
if 0 not in num:
print("Draw")
restart()
start(t,a,num)
def start(board,a,num):
if a%2==0:
p1n=int(input("Player 1, Enter a number from 1 to 9"))
if p1n not in num:
num[p1n-1]=p1n
print(num)
else:
print("Please enter in a free space")
start(board,a,num)
board[p1n-1]="X"
a=a+1
display_board(board,a,num)
else:
p2n=int(input("Player 2, Enter a number from 1 to 9"))
if p2n not in num:
num[p2n-1]=p2n
print(num)
else:
print("Please enter in a free space")
start(board,a,num)
board[p2n-1]="O"
a=a+1
display_board(board,a,num)
a=2
board=[" " for i in range(9)]
num=[0 for i in range(9)]
win = [[0,1,2],[3,4,5],[6,7,8],[0,4,8],[6,4,2],[6,3,0],[7,4,1],[8,5,2]]
start(board,a,num)