使用Python编写一个简单的tic-tac-toe游戏的教程


Posted in Python onApril 16, 2015

 这个教程,我们将展示如何用python创建一个井字游戏。 其中我们将使用函数、数组、if条件语句、while循环语句和错误捕获等。

首先我们需要创建两个函数,第一个函数用来显示游戏板:
 

def print_board():
  for i in range(0,3):
    for j in range(0,3):
      print map[2-i][j],
      if j != 2:
        print "|",
    print ""

这我们使用两个for循环来遍历map,该map是一个包含了位置信息的二维数组。

游戏板看起来是这样的:
 

|  | 
|  | 
|  |
 
X | X | 
O | X | O
 | O | X
 
X | X | X
X | X | X
X | X | X

 
下面我们需要一个函数check_done()来检查游戏是否结束。如果结束,则返回True并打印消息。
 

def check_done():
  for i in range(0,3):
    if map[i][0] == map[i][1] == map[i][2] != " " \
    or map[0][i] == map[1][i] == map[2][i] != " ":
      print turn, "won!!!"
      return True
     
  if map[0][0] == map[1][1] == map[2][2] != " " \
  or map[0][2] == map[1][1] == map[2][0] != " ":
    print turn, "won!!!"
    return True
 
  if " " not in map[0] and " " not in map[1] and " " not in map[2]:
    print "Draw"
    return True
     
  return False

有几个地方需要检查,首先检查水平和垂直方向,是否有一行或一列不为空且包含有三个相同的符号,然后我们再检查斜方向。如果上面有一个方向满足,游戏结束并打印“Won!!!”。请注意检查变量改变,它用来标记当前是哪一位玩家。

同时我们需要检查当前游戏板是否被填满且没有人获胜,游戏平局。

有了上面的两个函数,下面我们创建3个变量:
 

turn = "X"
map = [[" "," "," "],
    [" "," "," "],
    [" "," "," "]]
done = False

    turn : 轮到谁
    map : 游戏板
    done : 游戏是否结束

现在启动游戏:
 

while done != True:
  print_board()
   
  print turn, "'s turn"
  print
 
  moved = False
  while moved != True:

这里使用了while循环直到游戏结束并返回true.在这个循环里面,使用了另外一个while循环来检查玩家是否移动,如果玩家没有移动,则程序会跳到下一次循环。

下一步告诉玩家怎么玩:
 

print "Please select position by typing in a number between 1 and 9, see below for which number that is which position..."
    print "7|8|9"
    print "4|5|6"
    print "1|2|3"
    print
 
try:
      pos = input("Select: ")
      if pos <=9 and pos >=1:

我们期望玩家输入一个数字,检查该数字是否是在1到9之间。另外,我们这里需要一段错误处理逻辑,我们还需要需要检查玩家是否能移动到一个位置:
 

Y = pos/3
        X = pos%3
        if X != 0:
          X -=1
        else:
           X = 2
           Y -=1

以下是全部的代码:
 

def print_board():
  for i in range(0,3):
    for j in range(0,3):
      print map[2-i][j],
      if j != 2:
        print "|",
    print ""
 
 
def check_done():
  for i in range(0,3):
    if map[i][0] == map[i][1] == map[i][2] != " " \
    or map[0][i] == map[1][i] == map[2][i] != " ":
      print turn, "won!!!"
      return True
     
  if map[0][0] == map[1][1] == map[2][2] != " " \
  or map[0][2] == map[1][1] == map[2][0] != " ":
    print turn, "won!!!"
    return True
 
  if " " not in map[0] and " " not in map[1] and " " not in map[2]:
    print "Draw"
    return True
     
 
  return False
 
 
 
 
 
turn = "X"
map = [[" "," "," "],
    [" "," "," "],
    [" "," "," "]]
done = False
 
 
while done != True:
  print_board()
   
  print turn, "'s turn"
  print
 
  moved = False
  while moved != True:
    print "Please select position by typing in a number between 1 and 9,\
    see below for which number that is which position..."
    print "7|8|9"
    print "4|5|6"
    print "1|2|3"
    print
 
    try:
      pos = input("Select: ")
      if pos <=9 and pos >=1:
        Y = pos/3
        X = pos%3
        if X != 0:
          X -=1
        else:
           X = 2
           Y -=1
           
        if map[Y][X] == " ":
          map[Y][X] = turn
          moved = True
          done = check_done()
 
          if done == False:
            if turn == "X":
              turn = "O"
            else:
              turn = "X"
         
       
    except:
      print "You need to add a numeric value"
Python 相关文章推荐
基于Python实现通过微信搜索功能查看谁把你删除了
Jan 27 Python
Python的numpy库中将矩阵转换为列表等函数的方法
Apr 04 Python
Python实现的简单计算器功能详解
Aug 25 Python
Python通用循环的构造方法实例分析
Dec 19 Python
Django 缓存配置Redis使用详解
Jul 23 Python
Python 最强编辑器详细使用指南(PyCharm )
Sep 16 Python
Python使用random模块生成随机数操作实例详解
Sep 17 Python
Django Channel实时推送与聊天的示例代码
Apr 30 Python
将tf.batch_matmul替换成tf.matmul的实现
Jun 18 Python
一文带你了解Python 四种常见基础爬虫方法介绍
Dec 04 Python
python上下文管理器异常问题解决方法
Feb 07 Python
Python 中数组和数字相乘时的注意事项说明
May 10 Python
Python基于scrapy采集数据时使用代理服务器的方法
Apr 16 #Python
在Python的gevent框架下执行异步的Solr查询的教程
Apr 16 #Python
使用Python的Treq on Twisted来进行HTTP压力测试
Apr 16 #Python
Python3中多线程编程的队列运作示例
Apr 16 #Python
使用Python脚本操作MongoDB的教程
Apr 16 #Python
使用Python中的greenlet包实现并发编程的入门教程
Apr 16 #Python
利用Python的Twisted框架实现webshell密码扫描器的教程
Apr 16 #Python
You might like
PHP 快速排序算法详解
2014/11/10 PHP
php实现对象克隆的方法
2015/06/20 PHP
php实现自定义中奖项数和概率的抽奖函数示例
2017/05/26 PHP
PHP十六进制颜色随机生成器功能示例
2017/07/24 PHP
PHP7扩展开发之基于函数方式使用lib库的方法详解
2018/01/15 PHP
PHP排序算法之直接插入排序(Straight Insertion Sort)实例分析
2018/04/20 PHP
Laravel5.4框架中视图共享数据的方法详解
2019/09/05 PHP
Jquery 例外被抛出且未被接住原因介绍
2013/09/04 Javascript
优化javascript的执行效率一些方法总结
2013/12/25 Javascript
关闭页面时window.location事件未执行的原因分析及解决方案
2014/09/01 Javascript
关于Jquery中的事件绑定总结
2016/10/26 Javascript
fullCalendar中文API官方文档
2017/02/07 Javascript
nodejs搭建本地服务器并访问文件的方法
2017/03/03 NodeJs
js时间查询插件使用详解
2017/04/07 Javascript
详解React-Router中Url参数改变页面不刷新的解决办法
2018/05/08 Javascript
vue指令只能输入正数并且只能输入一个小数点的方法
2018/06/08 Javascript
ES10 特性的完整指南小结
2019/03/04 Javascript
使用express获取微信小程序二维码小记
2019/05/21 Javascript
通过jQuery学习js类型判断的技巧
2019/05/27 jQuery
js回调函数仿360开机
2019/12/26 Javascript
[01:00:14]DOTA2官方TI8总决赛纪录片 真视界True Sight
2019/01/16 DOTA
解决pandas.DataFrame.fillna 填充Nan失败的问题
2018/11/06 Python
从DataFrame中提取出Series或DataFrame对象的方法
2018/11/10 Python
python的concat等多种用法详解
2018/11/28 Python
python函数调用,循环,列表复制实例
2020/05/03 Python
python实现杨辉三角的几种方法代码实例
2021/03/02 Python
香港优质食材和美酒专门店:FoodWise
2017/09/01 全球购物
蹦床仓库:Trampoline Warehouse
2018/12/06 全球购物
高三生物教学反思
2014/01/25 职场文书
国庆节文艺活动方案
2014/02/03 职场文书
档案信息化建设方案
2014/05/16 职场文书
环境卫生工作汇报材料
2014/10/28 职场文书
2015年幼儿园中班下学期工作总结
2015/05/22 职场文书
MySQL命令无法输入中文问题的解决方式
2021/08/30 MySQL
Nginx反向代理、重定向
2022/04/13 Servers
Golang 切片(Slice)实现增删改查
2022/04/22 Golang