使用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 相关文章推荐
pymongo实现控制mongodb中数字字段做加法的方法
Mar 26 Python
Python实现简单的代理服务器
Jul 25 Python
Python中操作mysql的pymysql模块详解
Sep 13 Python
python利用paramiko连接远程服务器执行命令的方法
Oct 16 Python
Python3 循环语句(for、while、break、range等)
Nov 20 Python
python3实现字符串的全排列的方法(无重复字符)
Jul 07 Python
python 自动去除空行的实例
Jul 24 Python
python如何求数组连续最大和的示例代码
Feb 04 Python
详解torch.Tensor的4种乘法
Sep 03 Python
pytorch中index_select()的用法详解
Jan 06 Python
python自动化之如何利用allure生成测试报告
May 02 Python
yolov5返回坐标的方法实例
Mar 17 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
Thinkphp微信公众号支付接口
2016/08/04 PHP
解决Laravel blade模板转义html标签的问题
2019/09/03 PHP
Locate a File Using a File Open Dialog Box
2007/06/18 Javascript
用javascript做拖动布局的思路
2008/05/31 Javascript
JavaScript中的eval()函数详解
2013/08/22 Javascript
Event altKey,ctrlKey,shiftKey属性解析
2013/12/18 Javascript
Javascript判断图片尺寸大小实例分析
2014/06/16 Javascript
JS获取随机数和时间转换的简单实例
2016/07/10 Javascript
Javascript中级语法快速入手
2016/07/30 Javascript
JS之获取样式的简单实现方法(推荐)
2016/09/13 Javascript
完美解决JS文件页面加载时的阻塞问题
2016/12/18 Javascript
JS实现超简单的汉字转拼音功能示例
2016/12/22 Javascript
js弹出窗口简单实现代码
2017/03/22 Javascript
js中bool值的转换及“&amp;&amp;”、“||”、 “!!”详解
2017/12/21 Javascript
利用CDN加速react webpack打包后的文件详解
2018/02/22 Javascript
nodejs实现的简单web服务器功能示例
2018/03/15 NodeJs
vue2.0 路由模式mode=&quot;history&quot;的作用
2018/10/18 Javascript
解决layer.open弹出框不能获取input框的值为空的问题
2019/09/10 Javascript
js对象简介与基本用法示例
2020/03/13 Javascript
[51:50]完美世界DOTA2联赛 Magma vs GXR 第一场 11.07
2020/11/10 DOTA
Python使用add_subplot与subplot画子图操作示例
2018/06/01 Python
使用python获取电脑的磁盘信息方法
2018/11/01 Python
pytz格式化北京时间多出6分钟问题的解决方法
2019/06/21 Python
Python操作多维数组输出和矩阵运算示例
2019/11/28 Python
jupyter notebook tensorflow打印device信息实例
2020/04/20 Python
selenium携带cookies模拟登陆CSDN的实现
2021/01/19 Python
使用css3背景渐变中的透明度来设置不同颜色的背景渐变
2014/03/31 HTML / CSS
用HTML5制作数字时钟的教程
2015/05/11 HTML / CSS
recorder.js 基于Html5录音功能的实现
2020/05/26 HTML / CSS
Rag & Bone官网:瑞格布恩高级成衣
2018/04/19 全球购物
文化与传播毕业生求职信
2014/03/09 职场文书
财务统计员岗位职责
2015/04/14 职场文书
2015年医院护理部工作总结
2015/04/23 职场文书
2016党校学习心得体会范文
2016/01/07 职场文书
个人业务学习心得体会
2016/01/25 职场文书
资产移交协议书
2016/03/24 职场文书