使用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 相关文章推荐
离线安装Pyecharts的步骤以及依赖包流程
Apr 23 Python
Python 实现数据库(SQL)更新脚本的生成方法
Jul 09 Python
Python从使用线程到使用async/await的深入讲解
Sep 16 Python
详解Python用户登录接口的方法
Apr 17 Python
python调用其他文件函数或类的示例
Jul 16 Python
Python学习笔记之For循环用法详解
Aug 14 Python
python数据化运营的重要意义
Nov 25 Python
django修改models重建数据库的操作
Mar 31 Python
Python实现自动签到脚本的示例代码
Aug 19 Python
Pycharm2020最新激活码|永久激活(附最新激活码和插件的详细教程)
Sep 29 Python
PyCharm2020.3.2安装超详细教程
Feb 08 Python
Python中使用subprocess库创建附加进程
May 11 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
239军机修复记
2021/03/02 无线电
用文本文件制作留言板提示(上)
2006/10/09 PHP
PHP 图像尺寸调整代码
2010/05/26 PHP
C#使用PHP服务端的Web Service通信实例
2014/04/08 PHP
javascript 进度条 实现代码
2009/07/30 Javascript
在JQuery dialog里的服务器控件 事件失效问题
2010/12/08 Javascript
js弹出层之1:JQuery.Boxy (二)
2011/10/06 Javascript
通过Javascript创建一个选择文件的对话框代码
2012/06/16 Javascript
浅析JavaScript中两种类型的全局对象/函数
2013/12/05 Javascript
javascript 判断页面访问方式电脑或者移动端
2016/09/19 Javascript
JS 获取HTML标签内的子节点的方法
2016/09/21 Javascript
jquery控制页面的展开和隐藏实现方法(推荐)
2016/10/15 Javascript
JS实现间歇滚动的运动效果实例
2016/12/22 Javascript
js数组与字符串常用方法总结
2017/01/13 Javascript
面试常见的js算法题
2017/03/23 Javascript
VUE v-for循环中每个item节点动态绑定不同函数的实例
2018/09/26 Javascript
使用Vue父子组件通信实现todolist的功能示例代码
2019/04/11 Javascript
微信小程序如何使用云开发
2019/05/17 Javascript
Vue.js中provide/inject实现响应式数据更新的方法示例
2019/10/16 Javascript
[01:59]DOTA2首部纪录片《Free to play》预告片
2014/03/12 DOTA
[43:14]Liquid vs Optic 2018国际邀请赛淘汰赛BO3 第二场 8.21
2018/08/22 DOTA
在Django的URLconf中使用命名组的方法
2015/07/18 Python
python输入整条数据分割存入数组的方法
2018/11/13 Python
Python模块的定义,模块的导入,__name__用法实例分析
2020/01/07 Python
python实现时间序列自相关图(acf)、偏自相关图(pacf)教程
2020/06/03 Python
基于Python实现天天酷跑功能
2021/01/06 Python
用canvas实现图片滤镜效果附演示
2013/11/05 HTML / CSS
日本PLST在线商店:日本时尚杂志刊载的人气服装
2016/12/10 全球购物
阿玛尼美妆加拿大官方商城:Giorgio Armani Beauty加拿大
2017/10/24 全球购物
销售文员岗位职责
2013/11/29 职场文书
财务部总监岗位职责
2014/03/12 职场文书
专家推荐信怎么写
2015/03/25 职场文书
MySql新手入门的基本操作汇总
2021/05/13 MySQL
浅谈@Value和@Bean的执行顺序问题
2021/06/16 Java/Android
python异步的ASGI与Fast Api实现
2021/07/16 Python
golang定时器
2022/04/14 Golang