使用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实现baidu hi自动登录的代码
Feb 10 Python
Python使用Selenium+BeautifulSoup爬取淘宝搜索页
Feb 24 Python
Python实现简单求解给定整数的质因数算法示例
Mar 25 Python
python交互模式下输入换行/输入多行命令的方法
Jul 02 Python
python中break、continue 、exit() 、pass终止循环的区别详解
Jul 08 Python
Django的models模型的具体使用
Jul 15 Python
python3.7 sys模块的具体使用
Jul 22 Python
python中的&amp;&amp;及||的实现示例
Aug 07 Python
flask利用flask-wtf验证上传的文件的方法
Jan 17 Python
PyQt5多线程防卡死和多窗口用法的实现
Sep 15 Python
python中time tzset()函数实例用法
Feb 18 Python
如何利用Python实现一个论文降重工具
Jul 09 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数组函数序列之array_pop() - 删除数组中的最后一个元素
2011/11/07 PHP
PHP递归遍历指定文件夹内的文件实现方法
2016/11/15 PHP
Yii框架分页实现方法详解
2017/05/20 PHP
不常用但很实用的PHP预定义变量分析
2019/06/25 PHP
在IE上直接编辑网页内容的js代码(IE地址栏js)
2009/04/27 Javascript
js 自动播放的实例代码
2013/11/19 Javascript
Jquery实现遮罩层的方法
2015/06/08 Javascript
浅谈JavaScript中运算符的优先级
2015/07/07 Javascript
jQuery实现的指纹扫描效果实例(附演示与demo源码下载)
2016/01/26 Javascript
使用jQuery加载html页面到指定的div实现方法
2016/07/13 Javascript
canvas学习之API整理笔记(一)
2016/12/29 Javascript
Bootstrap实现可折叠分组侧边导航菜单
2018/03/07 Javascript
Angular搜索场景中使用rxjs的操作符处理思路
2018/05/30 Javascript
微信开发之企业付款到银行卡接口开发的示例代码
2018/09/18 Javascript
使用flow来规范javascript的变量类型
2019/09/12 Javascript
JS中间件设计模式的深入探讨与实例分析
2020/04/11 Javascript
JavaScript布尔运算符原理使用解析
2020/05/06 Javascript
[01:51]2014DOTA2国际邀请赛 这个赛场没有失败者VGTi5再见
2014/07/23 DOTA
[00:30]明星选手化身超级英雄!2018DOTA2亚洲邀请赛全明星赛来临!
2018/04/06 DOTA
Python pickle模块用法实例
2015/04/14 Python
对python当中不在本路径的py文件的引用详解
2018/12/15 Python
详解python路径拼接os.path.join()函数的用法
2019/10/09 Python
Pytorch 的损失函数Loss function使用详解
2020/01/02 Python
python模拟实现斗地主发牌
2020/01/07 Python
python定义类self用法实例解析
2020/01/22 Python
学生如何注册Pycharm专业版以及pycharm的安装
2020/09/24 Python
CSS3实现曲线阴影和翘边阴影
2016/05/03 HTML / CSS
加拿大在线隐形眼镜专家:PerfectLens.ca
2016/11/19 全球购物
可持续木材、生态和铝制太阳镜:Proof Eyewear
2019/07/24 全球购物
内业资料员岗位职责
2014/01/04 职场文书
法学专业毕业生求职信
2014/06/12 职场文书
医德医风个人工作总结2014
2014/11/14 职场文书
2015年综治维稳工作总结
2015/04/07 职场文书
2015年教师党员个人总结
2015/11/24 职场文书
2016年保险公众宣传日活动总结
2016/04/05 职场文书
Win11电脑显示本地时间与服务器时间不一致怎么解决?
2022/04/05 数码科技