使用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 相关文章推荐
深入探究Django中的Session与Cookie
Jul 30 Python
对python程序内存泄漏调试的记录
Jun 11 Python
如何在django里上传csv文件并进行入库处理的方法
Jan 02 Python
利用nohup来开启python文件的方法
Jan 14 Python
python3正则提取字符串里的中文实例
Jan 31 Python
python创造虚拟环境方法总结
Mar 04 Python
PyCharm专业最新版2019.1安装步骤(含激活码)
Oct 09 Python
使用python自动追踪你的快递(物流推送邮箱)
Mar 17 Python
记一次django内存异常排查及解决方法
Aug 07 Python
详解Pycharm安装及Django安装配置指南
Sep 15 Python
python matplotlib库的基本使用
Sep 23 Python
Django windows使用Apache实现部署流程解析
Oct 12 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/02/27 PHP
关于php循环跳出的问题
2013/07/01 PHP
PHP根据IP判断地区名信息的示例代码
2014/03/03 PHP
php实现微信公众平台账号自定义菜单类
2014/12/02 PHP
PHP pthreads v3下worker和pool的使用方法示例
2020/02/21 PHP
JS 建立对象的方法
2007/04/21 Javascript
文本框获得焦点和失去焦点的判断代码
2012/03/18 Javascript
javascript实现焦点滚动图效果 具体方法
2013/06/24 Javascript
用RadioButten或CheckBox实现div的显示与隐藏
2013/09/21 Javascript
jQuery选择器全面总结
2014/01/06 Javascript
JSON+Jquery省市区三级联动
2016/01/13 Javascript
Javascript Function.prototype.bind详细分析
2016/12/29 Javascript
在javascript中,null>=0 为真,null==0却为假,null的值详解
2017/02/22 Javascript
vuejs绑定class和style样式
2017/04/11 Javascript
原生JS实现微信通讯录
2020/06/18 Javascript
关于Python元祖,列表,字典,集合的比较
2017/01/06 Python
python爬虫框架talonspider简单介绍
2017/06/09 Python
Opencv+Python实现图像运动模糊和高斯模糊的示例
2019/04/11 Python
Python读写文件基础知识点
2019/06/10 Python
Python自动生成代码 使用tkinter图形化操作并生成代码框架
2019/09/18 Python
python使用yield压平嵌套字典的超简单方法
2019/11/02 Python
win10下python2和python3共存问题解决方法
2019/12/23 Python
什么是python的id函数
2020/06/11 Python
Python预测2020高考分数和录取情况
2020/07/08 Python
美国知名艺术画网站:Art.com
2017/02/09 全球购物
英国工具中心:UK Tool Centre
2017/07/10 全球购物
高性能装备提升营地:Kammok
2019/02/27 全球购物
幼儿园校车司机的岗位职责
2014/01/30 职场文书
爱国演讲稿400字
2014/05/07 职场文书
求职信名称怎么写
2014/05/26 职场文书
2015年环境整治工作总结
2015/05/22 职场文书
地道战观后感300字
2015/06/04 职场文书
2016年党员学习廉政准则心得体会
2016/01/20 职场文书
小学体育队列队形教学反思
2016/02/16 职场文书
Python 流媒体播放器的实现(基于VLC)
2021/04/28 Python
Mysql数据库中datetime、bigint、timestamp来表示时间选择,谁来存储时间效率最高
2021/08/23 MySQL