刚开始编程(关于堆栈溢出的第一篇文章),并通过Python中最基本的东西。我尝试尽可能多地完成练习,以便更好地理解它是如何工作的。
最新的练习是制作游戏Tic Tac Toe。我终于通过大量的谷歌搜索得到了代码,但我不确定我错过了关于用作函数'draw()'的参数的局部变量。从我的代码的第一行可以看出,我必须导入模块副本并使用copy.deepcopy()从列表'board'中定义此函数内的局部变量。
函数'draw()'是从'play_game()'调用的,但没有复制列表变量'board',我最终覆盖了所有其他函数的列表。这导致程序的所有其他部分出错。
我错过了什么?对我的代码的任何其他评论都是最受欢迎的。
import copy
def draw(board):
#Draws the board game and converts numbers from game board list to X and O's
print()
bo = copy.deepcopy(board)
for i in range(3):
for b in range(3):
if bo[i][b] == 1:
bo[i][b] = "X"
elif bo[i][b] == 2:
bo[i][b] = "O"
else:
bo[i][b] = " "
for i in range(3):
print(" ---" * 3)
print("| %s | %s | %s |" % (bo[i][0], bo[i][1], bo[i][2]), end="\n")
print(" ---" * 3)
def winner(board):
# Checkis if there's a diagonal winner
if (board[0][0] == board[1][1] == board[2][2]) and board[1][1] != 0:
return board[1][1]
elif (board[0][2] == board[1][1] == board[2][0]) and board[1][1] != 0:
return board[1][1]
else:
for i in range(3):
#Checks if there's a winner in a row
if (board[i][0] == board[i][1] == board[i][2]) and board[i][i] != 0:
return board[i][i]
#Checks if there's a winner in a column
elif (board[0][i] == board[1][i] == board[2][i]) and board[i][i] != 0:
return board[i][i]
return 0
def player_input(board, turn):
print("Enter a coordinate (row,column) for your choice, eg. '2,3'")
while True:
player = input("Player " + str(turn) + ": ")
try:
cor = player.split(",")
row = int(cor[0]) - 1
col = int(cor[1]) - 1
if board[row][col] == 0:
board[row][col] = turn
return board
else:
print("This space is allready occupied, please choose another coordinate.")
except:
print("Your choice raised an error, please try again.")
def play_again():
play = input("This was fun! Play again? (y/n): ")
if play == "y":
return True
else:
return False
def player_turn(turn):
# Returns what player is to go next
if turn == 1:
return 2
else:
return 1
def play_game():
# This method run all other functions in a single gameplay, and exits when the game is over
# Set all initial variables used in a new game
game = [[0,0,0],[0,0,0],[0,0,0]]
turn = 1
count = 0
win = 0
while True:
draw(game)
game = player_input(game, turn)
count += 1
win = winner(game)
if count == 9 and win == 0:
print("It's a draw!")
return
elif win != 0:
print("Player " + str(win) + " won!")
return
turn = player_turn(turn)
if __name__ == "__main__":
''' This is the game Tic, Tac, Toe. When run as a standalone script the game will
be initialized from the main method. When game is over the user will be prompted
to play again... '''
print("\n\n" + "---------- WELCOME TO TIC, TAC TOE. LET'S PLAY! ----------\n\n")
play = True
while play:
play_game()
play = play_again()