欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 用 Python 编写的井字游戏

用 Python 编写的井字游戏

2024/10/25 4:24:13 来源:https://blog.csdn.net/xiefeng240601/article/details/140857618  浏览:    关键词:用 Python 编写的井字游戏

一.介绍

在本文中,我将向您展示如何使用 Python 创建一个非常简单的井字游戏。

井字游戏是一种非常简单的双人游戏。因此每次只能有两个玩家玩。该游戏也称为井字游戏或 Xs 和 Os 游戏。一个玩家玩 X,另一个玩家玩 O。在这个游戏中,我们有一个由 3X3 网格组成的棋盘。网格数量可以增加。

井字棋棋盘如下所示

二.游戏规则

  1. 传统上,第一个玩家会用“X”来玩。因此,您可以决定谁想用“X”玩,谁想用“O”玩。
  2. 每次只能有一名玩家玩。
  3. 如果任何玩家已经填充了一个方格,那么另一个玩家和同一个玩家就不能覆盖该方格。
  4. 只有两种情况,可能匹配会打平或者获胜。
  5. 成功将三个相应的标记(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")
输出

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com