我的井字游戏运行良好。但是第一场比赛结束后,我在设计重播功能时遇到了麻烦?
My tic tac toe game is working fine. But I am having trouble designing replay functionality in it once the 1st game is over?
我设计了一个井字游戏,当我只玩一个游戏时它运行良好。但是一旦第一场比赛成功结束,我就无法在其中实现重播功能。
我已将 player_position 声明为全局。它存储了每次移动后X和O的位置值。
player_position={'X':[],'O':[]}
我把井字游戏 table 做了如下:
def print_tic_tac_toe(values):
print("\n")
print("\t | |")
print("\t {} | {} | {}".format(values[0], values[1], values[2]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[3], values[4], values[5]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[6], values[7], values[8]))
print("\t | |")
print("\n")
以下是定义的值变量和上面调用的函数:
values=[' ' for x in range(9)]
print_tic_tac_toe(values)
然后我做了每一步后检查获胜条件和平局条件的功能:
def winning_condition(player_position, current_player):
soln = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
for x in soln:
if set(x).issubset(player_position[current_player]):
return True
return False
def draw_condition(player_position):
if (len(player_position['X'])+len(player_position['O'])==9):
return True
return False
以下是重播功能,这是我面临的主要问题,想知道如何在我的主要功能中调用它:
def replay():
play_again=input('Do you want to play again? y/n :')
return (play_again=='y')
主要功能如下:
import random
def start_game():
toss=random.randint(0,1)
print ('Toss result is: ',toss)
if toss==0:
current_player='X'
print ('X will go first')
else:
current_player='O'
print ('O will go first')
while True:
print_tic_tac_toe(values)
print ('Enter your position player ', current_player)
move=int(input())
if move<0 or move>8:
print('Position does not exist. Try again!!')
continue
if values[move]!=' ':
print('Position already occupied. Try again!!')
continue
values[move]=current_player
player_position[current_player].append(move)
if winning_condition(player_position, current_player):
print_tic_tac_toe(values)
print ('Congrats Player ', current_player, ' you have won the game')
print ('\n')
if not replay():
print ('Game Ended')
break
if draw_condition(player_position):
print_tic_tac_toe(values)
print ('Game Drawn')
print('\n')
if not replay():
print ('Game Ended')
break
if current_player=='X':
current_player='O'
else:
current_player='X'
现在我知道当我在 start_game 函数中检查 winning_condition 和 draw_condition 时将调用重放函数。但我不知道怎么办。我想要的是当我调用重播函数时,它应该给我一个空的井字游戏 table,然后从 player_position 中删除 X 和 O 的所有值。
以下是游戏结束后player_position清除X和O值的方法:
for k in player_position:
player_position[k]=[]
但我不知道如何使用它以及如何在第一场比赛结束后得到一个空的井字棋 table。非常感谢任何帮助我在此代码中设计重放功能的帮助。谢谢。
好的,有几件事发生了变化。我重写了你的电路板打印功能,因为它很乱,我想清理一下。我用的是unicode方框字符,你可以得到here.
现在重要的是:
replay()
函数现在可以确保用户的正确输入
- 现在都在主游戏循环中检查 win/draw return 来自
replay()
的布尔值,这意味着 start_game()
功能退出
- 脚本现在使用
if __name__ == "__main__"
模式,您可以阅读有关 here 的更多信息
player_position
和 values
变量现在完全局限于 start_game
函数的作用域
player_position
和 values
变量现在在 start_game()
的顶部初始化,以便在调用 start_game()
时创建一个新游戏
- 所有内插字符串现在都使用 f 字符串而不是内插
既然你已经掌握了这个,我建议你学习一些基本的 OOP,并将游戏板变成一个对象。
import random
def print_board(values):
s = """
\t . ┃ . ┃ .
\t━━━╋━━━╋━━━
\t . ┃ . ┃ .
\t━━━╋━━━╋━━━
\t . ┃ . ┃ .
"""
print(s.replace(".", "{}").format(*values))
def replay():
while True:
play_again = input("Do you want to play again? y/n :")
if play_again.lower() in ["y", "n"]:
return play_again.lower() == "y"
print("Invalid input!")
def winning_condition(player_position, current_player):
soln = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
for x in soln:
if set(x).issubset(player_position[current_player]):
return True
return False
def draw_condition(player_position):
if (len(player_position["X"]) + len(player_position["O"]) == 9):
return True
return False
def start_game():
player_position={"X": [], "O": []}
values = [" " for x in range(9)]
toss = random.randint(0, 1)
print(f"Toss result is: {toss}")
if toss == 0:
current_player = "X"
else:
current_player = "O"
print(f"{current_player} will go first")
while True:
print_board(values)
move = int(input(f"Enter your position player {current_player}: "))
if move < 0 or move > 8:
print("Position does not exist. Try again!!")
continue
if values[move] != " ":
print("Position already occupied. Try again!!")
continue
values[move] = current_player
player_position[current_player].append(move)
if winning_condition(player_position, current_player):
print_board(values)
print(f"Congrats Player {current_player}, you have won the game!")
return replay()
elif draw_condition(player_position):
print_board(values)
print("Game Drawn!")
return replay()
if current_player == "X":
current_player = "O"
else:
current_player = "X"
if __name__ == "__main__":
play_again = True
while play_again:
play_again = start_game()
print("Thanks for playing!")
这是游戏板现在的样子:
X ┃ O ┃ X
━━━╋━━━╋━━━
O ┃ O ┃ X
━━━╋━━━╋━━━
O ┃ X ┃ O
它在 Python REPL 中看起来没那么空洞。
我设计了一个井字游戏,当我只玩一个游戏时它运行良好。但是一旦第一场比赛成功结束,我就无法在其中实现重播功能。 我已将 player_position 声明为全局。它存储了每次移动后X和O的位置值。
player_position={'X':[],'O':[]}
我把井字游戏 table 做了如下:
def print_tic_tac_toe(values):
print("\n")
print("\t | |")
print("\t {} | {} | {}".format(values[0], values[1], values[2]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[3], values[4], values[5]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[6], values[7], values[8]))
print("\t | |")
print("\n")
以下是定义的值变量和上面调用的函数:
values=[' ' for x in range(9)]
print_tic_tac_toe(values)
然后我做了每一步后检查获胜条件和平局条件的功能:
def winning_condition(player_position, current_player):
soln = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
for x in soln:
if set(x).issubset(player_position[current_player]):
return True
return False
def draw_condition(player_position):
if (len(player_position['X'])+len(player_position['O'])==9):
return True
return False
以下是重播功能,这是我面临的主要问题,想知道如何在我的主要功能中调用它:
def replay():
play_again=input('Do you want to play again? y/n :')
return (play_again=='y')
主要功能如下:
import random
def start_game():
toss=random.randint(0,1)
print ('Toss result is: ',toss)
if toss==0:
current_player='X'
print ('X will go first')
else:
current_player='O'
print ('O will go first')
while True:
print_tic_tac_toe(values)
print ('Enter your position player ', current_player)
move=int(input())
if move<0 or move>8:
print('Position does not exist. Try again!!')
continue
if values[move]!=' ':
print('Position already occupied. Try again!!')
continue
values[move]=current_player
player_position[current_player].append(move)
if winning_condition(player_position, current_player):
print_tic_tac_toe(values)
print ('Congrats Player ', current_player, ' you have won the game')
print ('\n')
if not replay():
print ('Game Ended')
break
if draw_condition(player_position):
print_tic_tac_toe(values)
print ('Game Drawn')
print('\n')
if not replay():
print ('Game Ended')
break
if current_player=='X':
current_player='O'
else:
current_player='X'
现在我知道当我在 start_game 函数中检查 winning_condition 和 draw_condition 时将调用重放函数。但我不知道怎么办。我想要的是当我调用重播函数时,它应该给我一个空的井字游戏 table,然后从 player_position 中删除 X 和 O 的所有值。 以下是游戏结束后player_position清除X和O值的方法:
for k in player_position:
player_position[k]=[]
但我不知道如何使用它以及如何在第一场比赛结束后得到一个空的井字棋 table。非常感谢任何帮助我在此代码中设计重放功能的帮助。谢谢。
好的,有几件事发生了变化。我重写了你的电路板打印功能,因为它很乱,我想清理一下。我用的是unicode方框字符,你可以得到here.
现在重要的是:
replay()
函数现在可以确保用户的正确输入- 现在都在主游戏循环中检查 win/draw return 来自
replay()
的布尔值,这意味着start_game()
功能退出 - 脚本现在使用
if __name__ == "__main__"
模式,您可以阅读有关 here 的更多信息
player_position
和values
变量现在完全局限于start_game
函数的作用域player_position
和values
变量现在在start_game()
的顶部初始化,以便在调用start_game()
时创建一个新游戏- 所有内插字符串现在都使用 f 字符串而不是内插
既然你已经掌握了这个,我建议你学习一些基本的 OOP,并将游戏板变成一个对象。
import random
def print_board(values):
s = """
\t . ┃ . ┃ .
\t━━━╋━━━╋━━━
\t . ┃ . ┃ .
\t━━━╋━━━╋━━━
\t . ┃ . ┃ .
"""
print(s.replace(".", "{}").format(*values))
def replay():
while True:
play_again = input("Do you want to play again? y/n :")
if play_again.lower() in ["y", "n"]:
return play_again.lower() == "y"
print("Invalid input!")
def winning_condition(player_position, current_player):
soln = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
for x in soln:
if set(x).issubset(player_position[current_player]):
return True
return False
def draw_condition(player_position):
if (len(player_position["X"]) + len(player_position["O"]) == 9):
return True
return False
def start_game():
player_position={"X": [], "O": []}
values = [" " for x in range(9)]
toss = random.randint(0, 1)
print(f"Toss result is: {toss}")
if toss == 0:
current_player = "X"
else:
current_player = "O"
print(f"{current_player} will go first")
while True:
print_board(values)
move = int(input(f"Enter your position player {current_player}: "))
if move < 0 or move > 8:
print("Position does not exist. Try again!!")
continue
if values[move] != " ":
print("Position already occupied. Try again!!")
continue
values[move] = current_player
player_position[current_player].append(move)
if winning_condition(player_position, current_player):
print_board(values)
print(f"Congrats Player {current_player}, you have won the game!")
return replay()
elif draw_condition(player_position):
print_board(values)
print("Game Drawn!")
return replay()
if current_player == "X":
current_player = "O"
else:
current_player = "X"
if __name__ == "__main__":
play_again = True
while play_again:
play_again = start_game()
print("Thanks for playing!")
这是游戏板现在的样子:
X ┃ O ┃ X
━━━╋━━━╋━━━
O ┃ O ┃ X
━━━╋━━━╋━━━
O ┃ X ┃ O
它在 Python REPL 中看起来没那么空洞。