使用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中使用dom模块生成XML文件示例
Apr 05 Python
解析Python中的异常处理
Apr 28 Python
python实现带错误处理功能的远程文件读取方法
Apr 29 Python
Python中.join()和os.path.join()两个函数的用法详解
Jun 11 Python
Python基于xlrd模块操作Excel的方法示例
Jun 21 Python
python3.6使用pickle序列化class的方法
Oct 22 Python
python绘制彩虹图
Dec 16 Python
python+selenium 脚本实现每天自动登记的思路详解
Mar 11 Python
Python验证码截取识别代码实例
May 16 Python
python判断字符串以什么结尾的实例方法
Sep 18 Python
Python如何使用ConfigParser读取配置文件
Nov 12 Python
使用scrapy实现增量式爬取方式
Jun 21 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与php MySQL 之间的关系
2009/07/17 PHP
TP5框架使用QueryList采集框架爬小说操作示例
2020/03/26 PHP
[原创]js与自动伸缩图片 自动缩小图片的多浏览器兼容的方法总结
2007/03/12 Javascript
JSON 数据格式介绍
2012/01/13 Javascript
js 控制页面跳转的5种方法
2013/09/09 Javascript
Jquery 在页面加载后执行的几种方式
2014/03/14 Javascript
JS将光标聚焦在文本最后的实现代码
2014/03/28 Javascript
纯HTML5制作围住神经猫游戏-附源码下载
2015/08/23 Javascript
JavaScript常用判断写法大全(推荐)
2016/05/30 Javascript
AngularJs bootstrap搭载前台框架——基础页面
2016/09/01 Javascript
jquery遍历标签中自定义的属性方法
2016/09/17 Javascript
vue实现的双向数据绑定操作示例
2018/12/04 Javascript
基于jQuery实现可编辑的表格
2019/12/11 jQuery
ES6如何用一句代码实现函数的柯里化
2020/01/18 Javascript
python 自动提交和抓取网页
2009/07/13 Python
浅谈Python中列表生成式和生成器的区别
2015/08/03 Python
Python实现将MySQL数据库表中的数据导出生成csv格式文件的方法
2018/01/11 Python
Djang的model创建的字段和参数详解
2019/07/27 Python
Python爬虫程序架构和运行流程原理解析
2020/03/09 Python
python opencv进行图像拼接
2020/03/27 Python
python读取excel进行遍历/xlrd模块操作
2020/07/12 Python
python 实现一个简单的线性回归案例
2020/12/17 Python
澳大利亚当地社区首选的光学商店:1001 Optical
2019/08/24 全球购物
美国婴儿服装购物网站:Gerber Childrenswear
2020/05/06 全球购物
文秘专业自荐信
2013/10/14 职场文书
统计岗位职责
2014/02/21 职场文书
项目采购员岗位职责
2014/04/15 职场文书
财政专业大学生职业生涯规划书
2014/09/17 职场文书
党的群众路线教育实践活动方案
2014/10/31 职场文书
个人学习群众路线心得体会
2014/11/05 职场文书
财务工作失误检讨书
2015/02/19 职场文书
会计求职简历自我评价
2015/03/10 职场文书
2016年寒假社会实践活动总结
2015/03/27 职场文书
Python基础之常用库常用方法整理
2021/04/30 Python
python 爬取哔哩哔哩up主信息和投稿视频
2021/06/07 Python
Redis做数据持久化的解决方案及底层原理
2021/07/15 Redis