In this tutorial we are going to see how we can implement the tic tac toe game in Python. We can either make use of random numbers for the computer move or we can develop a simple algorithm which will play the role of a computer.

在本教程中,我们将了解如何在Python中实现井字游戏。 我们可以利用随机数来移动计算机,也可以开发一种简单的算法来扮演计算机的角色。

Let us first see the representation of our board. For the purpose of this tutorial every place in the board is given a number. The board will look like this.

首先让我们看一下董事会的代表情况。 出于本教程的目的,董事会中的每个位置都有一个编号。 董事会将看起来像这样。

So when we say the 9th position is being assigned an X it means the last box of the board will be assigned an X.

因此,当我们说第9个位置被分配为X时,这意味着木板的最后一个框将被分配为X。

Using Random Numbers:

使用随机数:

Here we can keep a list of blank spaces on the board. Everytime when it’s computer’s turn we will generate a random number between [0,size_of_list-1] and computer will play that the move on the number present on that index. Here is the code-snippet for the computer move using a random number generator.

在这里,我们可以在板上保留空白列表。 每次轮到计算机时,我们都会在[0,size_of_list-1]之间生成一个随机数,然后计算机将对该索引上存在的数字进行移动。 这是使用随机数生成器进行计算机移动的代码片段。

def computer_move():move=-1empty_place = []# If I can win, others don't matter.for i in range(1,10):if board[i-1] == i-1 :empty_place.append(i)if len(empty_place) > 0 :idx = random.randint(0,len(empty_place)-1)move = empty_place[idx]return make_move(board,computer,move)return (False,False)

Here empty_place will store all the positions on the board which are empty and then we will take a random positions from the list and make sure that the computer’s move.

在这里empty_place将存储板上所有空的位置,然后我们从列表中随机抽取一个位置并确保计算机移动。

Developing Computer Algorithm: 

开发计算机算法:

The algorithm will consist of five steps:

该算法将包括五个步骤:

  1. First we will see if there is a move that computer can make which will win the game. If there is so, take that move. Otherwise, go to step 2.

    首先,我们将看看计算机是否可以采取行动来赢得比赛。 如果是这样,那就采取行动。 否则,请执行步骤2。

  2. See if there is a move that player can make which will cause computer to lose game. If there is so, move there to block the player. Otherwise, go to step 3.

    查看玩家是否可以采取行动,这将导致计算机输掉游戏。 如果有,请移动到那里以阻止播放器。 否则,请转到步骤3。

  3. Check if any of the corner spaces (spaces 1, 3, 7, or 9) are free. If so, move there. If no corner piece is free, then go to step 4.

    检查是否有任何角落空间(空间1、3、7或9)可用。 如果是这样,请移到那里。 如果没有角码可用,则转到步骤4。

  4. Check if the center is free or not. If so, move there. If it isn’t, then go to step 5.

    检查中心是否免费。 如果是这样,请移到那里。 如果不是,请转到步骤5。

  5. Move on any of the side pieces (spaces 2, 4, 6, or 8). Now there are no more steps, because if execution reaches step 5 the side spaces are the only spaces left.

    在任何侧边上移动(空格2、4、6或8)。 现在没有更多的步骤了,因为如果执行到达步骤5,则仅剩下边距。

Our simple algorithm is now ready. Let us first complete other requirements and then we will see the code for this algorithm.

我们的简单算法现已准备就绪。 让我们首先完成其他要求,然后我们将看到该算法的代码。

We will need to display the board after every turn.

我们将需要在每转之后显示板。

For the board we will take a list of size 9 which will contain the position at the start and later they will be changed to X and O.

对于板,我们将采取大小9将包含在起始位置的列表,之后他们将被更改为 XO。

At the start of the game, we first need to decide player will get X or O and whose turn will be first. This can be either done automatically using random number or we can take input from user. For this tutorial we are doing it using random numbers.

在游戏开始时,我们首先需要确定玩家将获得X或O,并且其回合将是第一位。 这可以使用随机数自动完成,也可以从用户那里获取输入。 在本教程中,我们使用随机数进行操作。

We will then create a new board (i.e A list having values from 1 to 9).

然后,我们将创建一个新的面板(即,一个值从1到9的列表)。

To check if move is valid: 

要检查移动是否有效:

Everytime we are making a move we should keep in mind that the position should not be already occupied (If a position contain the X or O then its occupied otherwise it will contain position number).

每次我们移动时,都应记住该位置不应已经被占用(如果一个位置包含X或O,则该位置将被占用,否则将包含位置编号)。

To check if player has won: 

要检查玩家是否赢了:

To check if a player won we have to check 2 diagonal entries, 3 rows and 3 columns. We will make a list of all the winning combinations and go through each after every turn of player or computer to check if they won.

要检查玩家是否获胜,我们必须检查2条对角线,3行和3列。 我们将列出所有获胜组合的清单,并在每次转动玩家或计算机后逐一检查它们是否获胜。

The winning combinations are as below:

获奖组合如下:

Row-wise: (0,1,2), (3,4,5), (6,7,8)

逐行:(0,1,2),(3,4,5),(6,7,8)

Column-wise: (0,3,6), (1,4,7), (2,5,8)

列方式:(0,3,6),(1、4、7),(2、5、8)

Diagonal-wise: (0,4,8), (2,4,6)

对角方向:(0,4,8),(2,4,6)

To check next move of computer:

要检查计算机的下一步动作:

If in a turn computer cannot win and we aren’t blocking the players pieces then we have to decide what move computer will play (i.e. If we are at step 3 of algorithm). Now according to the preference of our algorithm we should first check corner places, then center and then the rest. So we will create a list which will store these steps in the correct order and we will go through this list and make our move.

如果转牌时计算机不能赢,并且我们没有挡住玩家的棋子,那么我们必须决定计算机将要进行的移动(即,如果我们处于算法的第3步)。 现在,根据我们算法的偏好,我们应该首先检查拐角位置,然后检查中心,然后检查其余部分。 因此,我们将创建一个列表,该列表将以正确的顺序存储这些步骤,然后我们将遍历该列表并继续进行操作。

Corner: (1,3,7,9)

角球:(1,3,7,9)

Center: (5)

中心:(5)

Others: (2,4,6,8).

其他:(2,4,6,8)。

Now let us see how the code looks :

现在让我们看一下代码的样子:

Python Tic Tac Toe游戏代码 (Python Tic Tac Toe Game Code)

import random
import sysboard=[i for i in range(0,9)]
player, computer = '',''moves=((1,7,3,9),(5,),(2,4,6,8))winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
# Table
tab=range(1,10)# Function to print the board
def print_board():x=1counter = 0for i in range(0,9):if board[i] == 'X' or board[i] == 'O' :print(board[i],end = ' ')else :print(" ",end = ' ')counter+=1if counter%3 ==0 :print("",end = '\n----------\n')else :print("| ",end='')# This function will decide player will play with X or O
def select_char():if random.randint(0,1) == 0:return ('X','O')return ('O','X')# Function to decide a valid move.
def can_move(brd, player, move):if move in tab and brd[move-1] == move-1:return Truereturn False# Function to check if win condition is satisfied.
def can_win(brd, player, move):places=[]x=0for i in brd:if i == player: places.append(x);x+=1win=Truefor tup in winners:win=Truefor ix in tup:if brd[ix] != player:win=Falsebreakif win == True:breakreturn windef make_move(brd, player, move, undo=False):if can_move(brd, player, move):brd[move-1] = playerwin=can_win(brd, player, move)if undo:brd[move-1] = move-1return (True, win)return (False, False)def random_move():move=-1empty_place = []# If I can win, others don't matter.for i in range(1,10):if board[i-1] == i-1 :empty_place.append(i)if len(empty_place) > 0 :idx = random.randint(0,len(empty_place)-1)move = empty_place[idx]return make_move(board,computer,move)return (False,False)# AI goes here
def computer_move():move=-1# If the computer can win in this turn, it will take the turn.for i in range(1,10):if make_move(board, computer, i, True)[1]:move=ibreakif move == -1:# If player can win next turn then we have to block that.for i in range(1,10):if make_move(board, player, i, True)[1]:move=ibreakif move == -1:# Otherwise, try to take one of the desired places.for tup in moves:for mv in tup:if move == -1 and can_move(board, computer, mv):move=mvbreakreturn make_move(board, computer, move)def is_full():for i in range(0,9):if board[i] == i:return Truereturn Falseplayer, computer = select_char()
print('Player is [%s] and computer is [%s]' % (player, computer))turn = random.randint(0,1)if turn == 0 :print("Player will play first.")
else :print("Computer will play first.")print_board()computer_move()print()result="It's a tie !!"while is_full():print_board()print('Make your move  [1-9] : ', end='')move = int(input())moved, won = make_move(board, player, move)if not moved:print(' >> Invalid number ! Try again !')continueif won:result=' You won !!'breakelif computer_move()[1]:result=' You lose !!'break;print_board()
print(result)

Output:

输出:

Player is [X] and computer is [O] Computer will play first. | | ———- | | ———- | | ———-

播放器为[X],计算机为[O]。 计算机将首先播放。 | | ———- | | ———- | | ————

O | | ———- | | ———- | | ———- Make your move [1-9] : 2 O | X | ———- | | ———- O | | ———- Make your move [1-9] : 4 O | X | O ———- X | | ———- O | | ———- Make your move [1-9] : 5 O | X | O ———- X | X | O ———- O | | ———- Make your move [1-9] : 8 O | X | O ———- X | X | O ———- O | X | ———- You won !!

O | | ———- | | ———- | | ———- 行动[1-9]:2 O | X | ———- | | ———- O | | ———- 行动[1-9]:4 O | X | O ———- X | | ———- O | | ———- 行动[1-9]:5 O | X | O ———- X | X | O ———- O | | ———- 行动[1-9]:8 O | X | O ———- X | X | O ———- O | X | ------- 你赢了!

In the replace computer_move with random_move in the function calling then the computer will take random moves instead of using the algorithm as discussed before.

在函数调用中用random_move替换computer_move的情况下,计算机将采取随机移动的方式,而不是使用前面讨论的算法。

Commet down below if you have any queries related to python tic tac toe game implementation.

如果您有任何有关python tic tac toe游戏实现的查询,请在下面关注。

翻译自: https://www.thecrazyprogrammer.com/2019/11/python-tic-tac-toe-game.html

Python Tic Tac Toe游戏相关推荐

  1. python游戏代码运行不了_无法使我的tic tac toe游戏在python中正确运行

    转不到"玩家1"的原因是你的支票中缺少一个空格.你也没有正确地检查一个玩家何时获胜,这就是为什么你会有这种奇怪的行为.你需要检查每个位置,而不仅仅是最后一个.我还添加了对用户输入的 ...

  2. python井字棋游戏代码_Python实现的井字棋(Tic Tac Toe)游戏示例

    Python实现的井字棋(Tic Tac Toe)游戏示例 来源:中文源码网    浏览: 次    日期:2018年9月2日 [下载文档:  Python实现的井字棋(Tic Tac Toe)游戏示 ...

  3. react中使用构建缓存_通过在React中构建Tic Tac Toe来学习ReasonML

    react中使用构建缓存 3. 7. 2018: UPDATED to ReasonReact v0.4.2 3. 7. 2018:更新为ReasonReact v0.4.2 You may have ...

  4. python二维游戏示例_Python实现的井字棋(Tic Tac Toe)游戏示例

    本文实例讲述了Python实现的井字棋(Tic Tac Toe)游戏.分享给大家供大家参考,具体如下: 说明 用python实现了井字棋,整个框架是本人自己构思的,自认为比较满意.另外,90%+的代码 ...

  5. python井字棋ai,python 井字棋(Tic Tac Toe)

    说明 用python实现了井字棋,整个框架是本人自己构思的,自认为比较满意.另外,90%+的代码也是本人逐字逐句敲的. minimax算法还没完全理解,所以参考了这里的代码,并作了修改. 特点 可以选 ...

  6. Principle of Computing (Python)学习笔记(7) DFS Search + Tic Tac Toe use MiniMax Stratedy

    1. Trees Tree is a recursive structure. 1.1 math nodes https://class.coursera.org/principlescomputin ...

  7. amazon.设计1. tic tac toe

    //不觉中 已经全力找工作好久好久了.大概有1年半了.身心疲惫,不要放弃.曙光快来了. 1.tic tac toe //http://www.ntu.edu.sg/home/ehchua/progra ...

  8. C++ 很有趣:编写一个井字游戏 (Tic Tac Toe)

    英文原文:C++ is fun: Writing a Tic Tac Toe Game 这个有趣的C++系列打算展示一下使用C++写代码可以和其他主流语言一样高效而有趣.在第二部分,我将向你展示使用C ...

  9. 圈叉游戏 java_【炫光圈叉棋】炫光圈叉棋 Tic Tac Toe Glow 1.8.1下载_安卓(android)软件下载-魅族溜...

    一款炫光风格的圈叉棋游戏,支持单/双人模式.圈叉棋,英文:tic-tac-toe,别名:圈叉游戏.是一种游戏,3*3的9个方格子,先下者画圈,后下者画叉,每人可以在任意没有对方棋子的封闭方格里下一次, ...

  10. python井字棋_python 井字棋(Tic Tac Toe)

    说明 用python实现了井字棋,整个框架是本人自己构思的,自认为比较满意.另外,90%+的代码也是本人逐字逐句敲的. minimax算法还没完全理解,所以参考了这里的代码,并作了修改. 特点 可以选 ...

最新文章

  1. python学习笔记系列----(五)输入和输出
  2. 软件测试之Selenium IDE
  3. 【REST】REST和JAX-RS相关知识介绍
  4. Tcp连接的七次握手浅析
  5. Ionic混合移动app框架学习
  6. 移动端页面按手机屏幕分辨率自动缩放的js
  7. python numpy安装失败_解决python3.x安装numpy成功但import出错的问题
  8. XMLHttpRequest对象AJAX技术的基本使用
  9. Docker时代来临,你的团队准备好了吗?
  10. mongodb之mongostat 的字段含义解析
  11. MTK: mtk 10A 建立socket连接问题
  12. TLS协议簇加解密流程
  13. 回溯法之迷宫问题(华为笔试题)
  14. 有哪些毕设免费查重和降重的网站
  15. 批评性思维工具第11章 应对自身非理性
  16. 【计算广告】边际成本的妙用
  17. 美和易思——互联网技术学院返校周测题
  18. javaSE之多线程vip插队
  19. Dapr for dotnet | 密钥管理 - Secret Management
  20. 5种常用的四轴飞行器PID算法讲解集合

热门文章

  1. python 100days github_GitHub - 1042970366/Python-100-Days: Python - 100天从新手到大师
  2. 【源码】食肉植物算法Carnivorous Plant Algorithm (CPA)
  3. 忘记windows密码怎么办,教你五招!
  4. 狐妖小红娘手游服务器维护多久,狐妖小红娘手游:《狐妖小红娘》手游停服公告...
  5. c语言解惑 指针 数组 函数和多文件编程,C语言解惑 指针、数组、函数和多文件编程...
  6. Filebeat日志采集
  7. 趁年轻,多尝试一些富有挑战的工作吧
  8. 安卓毕业设计源码基于Uniapp+SSM实现的校园心理健康APP
  9. 疯狂原始人服务器维修,疯狂原始人服务器互通详解 安卓和ios能一起玩么
  10. 九鼎无双一面面经【凉】