一.介绍
在本文中,我将向您展示如何使用 Python 创建一个非常简单的井字游戏。
井字游戏是一种非常简单的双人游戏。因此每次只能有两个玩家玩。该游戏也称为井字游戏或 Xs 和 Os 游戏。一个玩家玩 X,另一个玩家玩 O。在这个游戏中,我们有一个由 3X3 网格组成的棋盘。网格数量可以增加。
井字棋棋盘如下所示
二.游戏规则
- 传统上,第一个玩家会用“X”来玩。因此,您可以决定谁想用“X”玩,谁想用“O”玩。
- 每次只能有一名玩家玩。
- 如果任何玩家已经填充了一个方格,那么另一个玩家和同一个玩家就不能覆盖该方格。
- 只有两种情况,可能匹配会打平或者获胜。
- 成功将三个相应的标记(X 或 O)放置在水平、6. 垂直或对角线上的玩家获胜。
三.获胜条件
谁在水平、垂直或对角线上放置三个相应的标记(X 或 O)谁就是获胜者。
游戏的代码如下
import os
import timeboard = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player = 1# Win Flags
Win = 1
Draw = -1
Running = 0
Stop = 1Game = Running
Mark = 'X'def DrawBoard():print(" %c | %c | %c " % (board[1], board[2], board[3]))print("___|___|___")print(" %c | %c | %c " % (board[4], board[5], board[6]))print("___|___|___")print(" %c | %c | %c " % (board[7], board[8], board[9]))print(" | | ")def CheckPosition(x):if board[x] == ' ':return Trueelse:return Falsedef CheckWin():global Gameif board[1] == board[2] and board[2] == board[3] and board[1] != ' ':Game = Winelif board[4] == board[5] and board[5] == board[6] and board[4] != ' ':Game = Winelif board[7] == board[8] and board[8] == board[9] and board[7] != ' ':Game = Winelif board[1] == board[4] and board[4] == board[7] and board[1] != ' ':Game = Winelif board[2] == board[5] and board[5] == board[8] and board[2] != ' ':Game = Winelif board[3] == board[6] and board[6] == board[9] and board[3] != ' ':Game = Winelif board[1] == board[5] and board[5] == board[9] and board[5] != ' ':Game = Winelif board[3] == board[5] and board[5] == board[7] and board[5] != ' ':Game = Winelif board[1] != ' ' and board[2] != ' ' and board[3] != ' ' and \board[4] != ' ' and board[5] != ' ' and board[6] != ' ' and \board[7] != ' ' and board[8] != ' ' and board[9] != ' ':Game = Drawelse:Game = Runningprint("Tic-Tac-Toe Game Designed By Sourabh Somani")
print("Player 1 [X] --- Player 2 [O]\n")
print()
print()
print("Please Wait...")
time.sleep(3)while Game == Running:os.system('cls')DrawBoard()if player % 2 != 0:print("Player 1's chance")Mark = 'X'else:print("Player 2's chance")Mark = 'O'choice = int(input("Enter the position between [1-9] where you want to mark: "))if CheckPosition(choice):board[choice] = Markplayer += 1CheckWin()os.system('cls')DrawBoard()if Game == Draw:print("Game Draw")elif Game == Win:player -= 1if player % 2 != 0:print("Player 1 Won")else:print("Player 2 Won")