如何制作井字游戏 Python 带有代码示例

井字游戏 Python 是一个你可以尝试的有趣项目。这是一个很酷很有趣的解决挑战的项目,可以帮助你掌握 Python。创建有趣的井字游戏有助于提高您的技能。

你可以使用一个好的 Python 编辑器,例如 Pycharm 或命令行界面。

如何玩 Tic Toc 游戏?

井字游戏是一种简单的双人游戏,任何人都可以玩,不需要游戏板。游戏需要两名玩家标记不同的格子,直到游戏结束,获胜或平局。

以下是井字游戏的玩法。

步骤1) 井字游戏从方格中的空格开始。这是井字棋盘。

步骤2) 两位玩家从两个符号中选择,通常是 X 或 O。您可以使用游戏中的任何其他独特符号。

步骤3) 当前玩家轮流标记,填写井字棋盘上的单元格,直到有玩家填写获胜组合。即整行、整列或整对角线都有相同的符号。

步骤4) 如果所有格子都满了,没有明显的赢家,也可能出现平局

操作系统需求

建立 井字游戏 Python 项目 需要初级水平的理解 Python 编程语言。它包括理解“for”循环和迭代,以及 if 语句在 Python.

您还需要 Python 和 Python 安装在计算机上的文本编辑器来完成井字游戏 Python 项目。由于这是一个初级井字游戏, Python,你不需要任何 Python 图书馆。

您可能需要一些调试技能才能找到代码中错误的解决方案,并且您还应该对游戏组件有足够的了解。

井字 Python 算法

按照以下步骤创建井字游戏 Python 编程语言:

步骤1) 创建棋盘以开始井字游戏。

步骤2) 请求用户决定游戏板的尺寸。

步骤3) 随机选择第一个玩家。

步骤4) 井字游戏开始了。

步骤5) 玩家通过选择棋盘上的空位来玩游戏。

步骤6) 用玩家的标志填充选定的空白位置。

步骤7) 使用游戏逻辑确定玩家是否获胜或平局。

步骤8) 如果没有玩家获胜或者与第二位玩家打平,则每次游戏后显示游戏板。

步骤9) 分别显示平局或胜利的信息。

步骤10) 结束井字游戏并选择开始新游戏。

全 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 先播放它。