这是我尝试制作的第一个程序。它是一个简单的游戏,包括零和十字架。它用Python 3.6编写。
我已经测试了它,当游戏结束时,领带/赢取消息被打印两次,但我看不出原因。
对此或任何其他改进的任何帮助表示赞赏。非常感谢。
我只包含了播放器1代码,因此我可以发布问题。
#Grid
grid = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print("Welcome to Noughts and Crosses Game")
p1_name = input("What is name of Player 1? Player 1 is 'x': ")
#Draw Grid
def draw_grid():
print("-------------")
print('|', grid[0], '|', grid[1], '|', grid[2], '|')
print("-------------")
print('|', grid[3], '|', grid[4], '|', grid[5], '|')
print("-------------")
print('|', grid[6], '|', grid[7], '|', grid[8], '|')
print("-------------")
#Move input for player 1
def p1():
try:
p1_input = int(input(p1_name + " select a space on the grid by entering a \
number to place an 'x': "))
except ValueError:
print("Error: Please enter a number, not a letter or symbol")
p1()
else:
if p1_input not in range(9):
print("Error: Please select a number on the grid 0-8 to place an 'x'")
p1()
elif grid[p1_input] == "x" or grid[p1_input] == "o":
print("Error: This spot has been taken.")
p1()
else:
grid[p1_input] = "x"
draw_grid()
#Check for three x in a row
def p1_check():
if grid[0] == "x" and grid[1] == "x" and grid[2] == "x" or \
grid[3] == "x" and grid[4] == "x" and grid[5] == "x" or \
grid[6] == "x" and grid[7] == "x" and grid[8] == "x" or \
grid[0] == "x" and grid[3] == "x" and grid[6] == "x" or \
grid[1] == "x" and grid[4] == "x" and grid[7] == "x" or \
grid[2] == "x" and grid[5] == "x" and grid[8] == "x" or \
grid[6] == "x" and grid[4] == "x" and grid[2] == "x" or \
grid[0] == "x" and grid[4] == "x" and grid[8] == "x":
print(p1_name + " Wins!")
return "End Game"
#Check for a tie
def tie_check():
if grid.count("x") + grid.count("o") == len(grid):
print("Game is a tie")
return "End Game"
def play():
draw_grid()
while True:
p1()
p1_check()
if p1_check() == "End Game":
break
tie_check()
if tie_check() == "End Game":
break
play()
答案 0 :(得分:1)
p1_check()
if p1_check() == "End Game":
break
tie_check()
if tie_check() == "End Game":
break
您正在运行p1_check()和tie_check()两次。将p1_check()和tie_check()的输出存储在变量中以避免双重打印。
ended = p1_check()
if ended == "End Game":
break
tied = tie_check()
if tied == "End Game":
break
答案 1 :(得分:0)
因为p1_check和tie_check被执行了两次。 一次在if语句之前,然后再在if语句中
我建议删除if语句之前的调用