我正在用Python编写井字游戏。
这是我在Python中的第一个项目。如何减少代码的大小?例如,减少所有这些if语句(我知道但我想要社区的建议)。
我有一些想法,例如不使用'-'和store()函数预先初始化列表
l=['--','--','--','--','--','--','--','--','--']
j=0
def board():
print("Game Started...\n")
global l
print("%s\t%s\t%s\n" % (l[0], l[1], l[2]))
print("%s\t%s\t%s\n" % (l[3], l[4], l[5]))
print("%s\t%s\t%s\n" % (l[6], l[7], l[8]))
def status():
if (l[0] == l[3] == l[6] == 'X'):
print("Game Ended and Congrats Player 1..you won!!")
return False
elif (l[2] == l[5] == l[8] == 'X'):
print("Game Ended and Congrats Player 1..you won!!")
return False
elif (l[0] == l[1] == l[2] == 'X'):
print("Game Ended and Congrats Player 1..you won!!")
return False
elif (l[1] == l[4] == l[7] == 'X'):
print("Game Ended and Congrats Player 1..you won!!")
return False
elif (l[3] == l[4] == l[5] == 'X'):
print("Game Ended and Congrats Player 1..you won!!")
return False
elif (l[6] == l[7] == l[8] == 'X'):
print("Game Ended and Congrats Player 1..you won!!")
return False
elif (l[0] == l[4] == l[8] == 'X'):
print("Game Ended and Congrats Player 1..you won!!")
return False
elif (l[2] == l[4] == l[6] == 'X'):
print("Game Ended and Congrats Player 1..you won!!")
return False
elif (l[0] == l[3] == l[6] == 'O'):
print("Game Ended and Congrats Player 2...you Won!!")
return False
elif (l[2] == l[5] == l[8] == 'O'):
print("Game Ended and Congrats Player 2...you Won!!")
return False
elif (l[0] == l[1] == l[2] == 'O'):
print("Game Ended and Congrats Player 2...you Won!!")
return False
elif (l[1] == l[4] == l[7] == 'O'):
print("Game Ended and Congrats Player 2...you Won!!")
return False
elif (l[3] == l[4] == l[5] == 'O'):
print("Game Ended and Congrats Player 2...you Won!!")
return False
elif (l[6] == l[7] == l[8] == 'O'):
print("Game Ended and Congrats Player 2...you Won!!")
return False
elif (l[0] == l[4] == l[8] == 'O'):
print("Game Ended and Congrats Player 2...you Won!!")
return False
elif (l[2] == l[4] == l[6] == 'O'):
print("Game Ended and Congrats Player 2...you Won!!")
return False
else:
return True
def store(value):
global j
j=value
def choice():
global j
c=input("Whose Turn?\nEnter 1 for P1\nEnter 2 for P2\n")
if(c!=j):
If (c.isdigit()):
store(c)
return int(c)
else:
print("Please Enter a valid number i.e 1 or 2\n")
c = input("Whose Turn?\nEnter 1 for P1\nEnter 2 for P2\n")
store(c)
return int(c)
else:
print("Already Turn Expired\n")
def Mark():
while(status()):
h=choice()
if (h == 1):
t = input("Enter position to mark\n")
p = int(t) - 1
l[p] = 'X'
board()
if (h== 2):
t = input("Enter position to mark\n")
p = int(t) - 1
l[p] = 'O'
board()
def game():
board()
Mark()
game()
此代码运行良好。我是新手,我只需要来自该论坛的一些宝贵建议即可。