使用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写的ARP攻击代码实例
Jun 04 Python
django模型中的字段和model名显示为中文小技巧分享
Nov 18 Python
使用rpclib进行Python网络编程时的注释问题
May 06 Python
python操作字典类型的常用方法(推荐)
May 16 Python
Tensorflow之Saver的用法详解
Apr 23 Python
python numpy 显示图像阵列的实例
Jul 02 Python
Python设计模式之组合模式原理与用法实例分析
Jan 11 Python
python使用pip安装SciPy、SymPy、matplotlib教程
Nov 20 Python
Python字符串的修改方法实例
Dec 19 Python
打包PyQt5应用时的注意事项
Feb 14 Python
python和pywin32实现窗口查找、遍历和点击的示例代码
Apr 01 Python
python 图像增强算法实现详解
Jan 24 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基础知识回顾
2012/08/16 PHP
php实现批量压缩图片文件大小的脚本
2014/07/04 PHP
PHP Warning: Module 'modulename' already loaded in问题解决办法
2015/03/16 PHP
PHP通过GD库实现验证码功能示例
2019/02/23 PHP
Yii框架布局文件的动态切换操作示例
2019/11/11 PHP
firefox中JS读取XML文件
2006/12/21 Javascript
javascript 函数及作用域总结介绍
2013/11/12 Javascript
按Enter键触发事件的jquery方法实现代码
2014/02/17 Javascript
jQuery .tmpl() 用法示例介绍
2014/08/21 Javascript
javascript中scrollTop详解
2015/04/13 Javascript
11种ASP连接数据库的方法
2015/09/18 Javascript
js全选按钮的实现方法
2015/11/17 Javascript
js创建数组的简单方法
2016/07/27 Javascript
详解angularjs中如何实现控制器和指令之间交互
2017/05/31 Javascript
node.js文件操作系统实例详解
2019/11/05 Javascript
vuex存取值和映射函数使用说明
2020/07/24 Javascript
解决vue动态下拉菜单 有数据未反应的问题
2020/08/06 Javascript
解决vuex改变了state的值,但是页面没有更新的问题
2020/11/12 Javascript
基于python yield机制的异步操作同步化编程模型
2016/03/18 Python
浅谈Python类里的__init__方法函数,Python类的构造函数
2016/12/10 Python
python3.5 + PyQt5 +Eric6 实现的一个计算器代码
2017/03/11 Python
使用EduBlock轻松学习Python编程
2018/10/08 Python
python合并已经存在的sheet数据到新sheet的方法
2018/12/11 Python
树莓派使用USB摄像头和motion实现监控
2019/06/22 Python
如何爬取通过ajax加载数据的网站
2019/08/15 Python
使用python去除图片白色像素的实例
2019/12/12 Python
Python 3 使用Pillow生成漂亮的分形树图片
2019/12/24 Python
解决paramiko执行命令超时的问题
2020/04/16 Python
5分钟让你掌握css3阴影、倒影、渐变小技巧(小编推荐)
2016/08/15 HTML / CSS
意大利在线药房:Saninforma
2021/02/11 全球购物
早餐连锁店计划书
2014/01/08 职场文书
员工拾金不昧表扬信
2014/01/09 职场文书
保护环境倡议书100字
2014/05/19 职场文书
整顿机关作风心得体会
2014/09/10 职场文书
GTX1660显卡搭配显示器推荐
2022/04/19 数码科技
js作用域及作用域链工作引擎
2022/07/07 Javascript