如何在 Python 中使用代码示例制作井字棋游戏
Python 中的井字棋游戏是一个有趣的项目,您可以尝试一下。这是一个很酷且有趣的挑战性项目,可以帮助您掌握 Python 的基本概念。创建有趣的井字棋游戏有助于您提高技能。
您可以使用 PyCharm 或命令行界面等良好的 Python 编辑器。
如何玩井字棋游戏?
井字棋游戏是一款简单的两人游戏,任何人都可以玩,无需游戏板。它涉及两名玩家在棋盘上标记不同的单元格,直到游戏结束,以赢或平局告终。
这是如何玩井字棋游戏的。
第一步) 井字棋游戏开始时,棋盘上的单元格是空的。这就是井字棋棋盘。
第二步) 两名玩家选择两种符号,通常是 X 或 O。您可以在游戏中选择任何其他唯一的符号。
第三步) 当前玩家轮流通过填充井字棋棋盘的单元格来标记,直到一名玩家填满获胜组合。即整行、整列或对角线都带有相同的符号。
第四步) 如果所有单元格都已填满但没有明显赢家,则也可能出现平局。
需求
构建井字棋 Python 项目需要对 Python 编程语言有初级水平的了解。它包括了解“for”循环和迭代,以及 Python 中 if 语句的用途。
您还需要在计算机上安装 Python 和 Python 文本编辑器才能完成井字棋 Python 项目。由于这是一个初学者级别的 Python 井字棋游戏,您不需要任何 Python 库。
您可能需要一些调试技巧来找到代码中错误的解决方案,并且您还应该充分了解游戏组件。
井字棋 Python 算法
请按照以下步骤使用 Python 编程语言创建井字棋游戏
第一步) 创建棋盘以开始井字棋游戏。
第二步) 请求用户决定游戏棋盘的尺寸。
第三步) 随机选择第一位玩家。
第四步) 井字棋游戏开始。
第五步) 玩家通过选择棋盘上的一个空位来玩。
第六步) 用玩家的符号填充选定的空位。
第七步) 使用游戏逻辑确定玩家在游戏中获胜还是平局。
第八步) 如果没有任何玩家获胜或平局,则在每次游戏后向第二位玩家显示游戏棋盘。
第九步) 分别显示平局或获胜消息。
第十步) 结束井字棋游戏,并提供开始新游戏的选项。
完整的井字棋 Python 代码
# Guru99 # Code developed by Guru99.com # Guru99 tic-tac-toe game #Get input def getInput(prompt, cast=None, condition=None, errorMessage=None): while True: try: val = cast(input(prompt)) assert condition is None or condition(val) return val except: print(errorMessage or "Invalid input.") # Print the game board def printBoard(board): print() for row in board: print(*row) print() # Check if player won using the winning combinations def checkWin(board): # Check rows for row in range(len(board)): for col in range(len(board)-1): if board[row][col] == "_" or board[row][col+1] == "_" or board[row][col] != board[row][col+1]: break else: return True # Check column numbers for col in range(len(board)): for row in range(len(board)-1): if board[row][col] == "_" or board[row+1][col] == "_" or board[row][col] != board[row+1][col]: break else: return True # Check left diagonal for cell in range(len(board)-1): if board[cell][cell] == "_" or board[cell+1][cell+1] == "_" or board[cell][cell] != board[cell+1][cell+1]: break else: return True # Check right diagonal for cell in range(len(board)-1): emptyCell = board[cell][len(board)-cell-1] == "_" or board[cell+1][len(board)-cell-2] == "_" different = board[cell][len(board)-cell-1] != board[cell+1][len(board)-cell-2] if emptyCell or different: break else: return True # No win return False # Play tic tac toe game def play(): # Introduction print("------------\nN-DIMENSIONAL TIC TAC TOE game by guru 99.com \n------------") # Set up variables N = getInput(prompt="Guru99 says>>> Enter N, the dimensions of the board: ", cast=int, condition=lambda x: x >= 3, errorMessage="Invalid input. Please enter an integer greater than or equal to 3 as explained on guru99.com") board = [['_'] * N for _ in range(N)] used = 0 turn = 0 # Play guru99 tic tac toe game in Python using while infinite loop while True: # Print guru99 tic tac toe game board printBoard(board) # Get user pick pick = getInput(prompt=f"Player {turn+1} - Pick location (row, col): ", cast=lambda line: tuple(map(int, line.split(" "))), condition=lambda pair: min(pair) >= 0 and max(pair) < N and board[pair[0]][pair[1]] == "_", errorMessage="Invalid input. Please enter a valid, unoccupied location as an integer pair.") # Populate location board[pick[0]][pick[1]] = "X" if turn == 0 else "O" used += 1 # Check for win #Guru99 tutorial if checkWin(board): printBoard(board) print(f"Game over, Player {turn+1} wins.") break # Check for tie elif used == N*N: printBoard(board) print("Game over. Players have tied the match.") print("Guru99.com tic tac toe game ") break # If no win yet, update next user turn = (turn+1)%2 # Check for rematch playAgain = getInput(prompt="Play Guru99 tic tac toe_Game again? (y/n): ", cast=str, condition=lambda ans: ans.strip("\n").lower() in {"y", "n"}, errorMessage="Invalid input. Please enter 'y' or 'n'.") if playAgain == 'n': # End the game print("\nGuru99 TicTacToe game ended.") return else: # Rematch play() # Main if __name__ == '__main__': play()
井字棋 Python 代码输出
运行上述源代码后,下面是 3 x 3 井字棋棋盘的预期输出
------------ N-DIMENSIONAL TIC TAC TOE game by guru 99.com ------------ Guru99 says>>> Enter N, the dimensions of the board: 3 _ _ _ _ _ _ _ _ _ Player 1 - Pick location (row, col): 1 1 _ _ _ _ X _ _ _ _ Player 2 - Pick location (row, col): 0 1 _ O _ _ X _ _ _ _ Player 1 - Pick location (row, col): 1 2 _ O _ _ X X _ _ _ Player 2 - Pick location (row, col): 0 2 _ O O _ X X _ _ _ Player 1 - Pick location (row, col): 1 0 _ O O X X X _ _ _ Game over, Player 1 wins. Play Guru99 tic tac toe_Game again? (y/n):
完整代码详解
在 Python 中创建井字棋很简单。让我们逐个剖析不同的函数,以了解每一行的作用
打印棋盘
井字棋棋盘是主要的比赛显示。在 Python 中,显示窗口用于显示游戏棋盘。
以下是帮助您为 Python 中的井字棋创建棋盘的步骤
Python 井字棋代码
def getInput(prompt, cast=None, condition=None, errorMessage=None): while True: try: val = cast(input(prompt)) assert condition is None or condition(val) return val except: print(errorMessage or "Invalid input.") # Print the board def printBoard(board): print() for row in board: print(*row) print() N = getInput(prompt="Guru99 says>>> Enter N, the dimensions of the board: ", cast=int, condition=lambda x: x >= 3, errorMessage="Invalid input. Please enter an integer greater than or equal to 3 as explained on guru99.com") board = [['_'] * N for _ in range(N)] used = 0 turn = 0 printBoard(board)
代码输出
------------ N-DIMENSIONAL TIC TAC TOE game by guru 99.com ------------ Guru99 says>>> Enter N, the dimensions of the board: 3 _ _ _ _ _ _ _ _ _
井字棋游戏 – 获胜排列
要检查是否有玩家获胜,我们需要检查行、列和对角线中的获胜组合。如果有赢家,我们需要显示获胜消息。
行
- 对于行,该函数获取每一对连续的列并检查获胜组合。
- 第一个填满行的玩家获胜。第二个玩家因此输掉。
- 如果连续两列相同,那么显然该行中的所有元素都相同。
- 如果其中两个不同,或者该行包含一个空单元格,则仍然没有赢家。
- 然后,我们实现失败条件并添加一个中断。如果任何这些失败条件成立,则我们在检查的行中没有赢家。
- else 语句返回 true,表示有赢家。
- break 语句会跳出此循环,继续到下一行。
列
对于列,我们重复与行相同的函数。在每位玩家落子后,我们都会检查是否有人获胜。
对角线获胜
对于左对角线,任务变得更简单了。我们将始终比较对角线中的单元格。但是,如果没有赢家,我们可以继续执行下一条指令。
游戏逻辑
这是主要的比赛函数。为此,我们可以使用存储信息的变量。
- 第一个变量是存储在“N”中的棋盘大小。游戏将在要求用户输入数字后获取棋盘大小。
- 因此,当您输入值时,它会被处理。
- 我们还可以创建一个错误消息,在玩家键入任何无效数字时显示。
- 然后,我们可以创建两个变量,当单元格被填充时,它们会填充“X”或“O”。
- 然后向玩家显示游戏棋盘。在此之后,获取玩家的输入。
- 然后,该逻辑将标记选定的单元格为已填充,并检查是否获胜或平局。
- 如果没有赢家,游戏会要求下一位玩家玩。如果有赢家或平局,游戏可以询问用户是否想要开始新游戏。
结论
- 井字棋是一款有趣的两人游戏,通过在空的棋盘单元格中放置唯一的符号来玩。
- 在 Python 中创建井字棋游戏需要对 Python 的初级知识、文本编辑器和已安装的 Python。
- 算法可帮助您以任何语言系统地编写代码。
- 要创建游戏,首先,绘制棋盘并编写代码以确定获胜和失败的排列
- 您可以通过先玩来测试 Python 中的井字棋代码。