基于python纯函数实现井字棋游戏


Posted in Python onMay 27, 2020

1、定义全局变

'''全局变量:
 X 和 O 表示两方的棋子;
 EMPTY 表示棋位为空;
 TIE 表示平局;
 NUM_SQUARES 表示有 9 个棋位
 '''
 X = "X"
 O = "O"
 EMPTY = " "
 TIE = "TIE"
 NUM_SQUARES = 9

2、定义调用到的函数

def ask_yes_no(question):
  '''问一个是或否的问题,用 y 或 n 回答。'''
  response = None
  while response not in ('y', 'n'):
    response = input(question).lower()
  return response


def ask_number(question, low, high):
  '''讯问一个规定范围的数字。'''
  response = None
  while response not in range(low, high):
    response = int(input(question))
  return response


def pieces():
  '''决定在人和机器之间谁先行棋。'''
  go_first = ask_yes_no('你先走? (y/n): ')
  if go_first == 'y':
    print('\n好,你先请。')
    human = X
    computer = O
  else:
    print('\n你放弃先手,我先走。')
    computer = X
    human = O
  return computer, human


def new_board():
  '''创建一个棋盘。'''
  board = []
  for square in range(NUM_SQUARES):
    board.append(EMPTY)
  return board


def display_board(board):
  '''显示棋盘。'''
  print('\n\t', board[0], '|', board[1], '|', board[2])
  print('\t', '---------')
  print('\t', board[3], '|', board[4], '|', board[5])
  print('\t', '---------')
  print('\t', board[6], '|', board[7], '|', board[8], '\n')


def legal_moves(board):
  '''创建合法的行棋位置清单。'''
  moves = []
  for square in range(NUM_SQUARES):
    if board[square] == EMPTY: # 该棋位为空
      moves.append(square)
  return moves


def winner(board):
  '''判定游戏获胜者。'''
  WAYS_TO_WIN = ((0, 1, 2), # 横
          (3, 4, 5),
          (6, 7, 8),
          (0, 3, 6), # 竖
          (1, 4, 7),
          (2, 5, 8),
          (0, 4, 8), # 主对角线
          (2, 4, 6)) # 副对角线
  # 谁先有三个棋子在一条直线上谁就获胜。
  for row in WAYS_TO_WIN:
    if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
      winner = board[row[0]]
      return winner
  
  # 没有获胜方,但棋盘已经下满,判为平局
  if EMPTY not in board:
    return TIE

  return None # 没有获胜方,且非平局


def human_move(board, human):
  '''获取玩家的行棋位置。''' 
  legal = legal_moves(board) # 合法的行棋位置清单
  move = None
  while move not in legal:
    move = ask_number('你走哪? (0 - 8):', 0, NUM_SQUARES)
    if move not in legal:
      print('\n你选的棋位已落子,重新选择。\n')
  print('落子无悔...')
  return move


def computer_move(board, computer, human):
  '''获取电脑的行棋位置。'''
  
  board = board[:] # 通过切片复制棋盘, 创建局部变量
  BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7) # 优先的行棋位置

  print('我走到:', end=' ')
  
  # 在局部空间确定可以获胜的走法
  for move in legal_moves(board): # 合法的行棋位置列表
    board[move] = computer # 更新棋盘副本
    if winner(board) == computer:
      # 计算机能获胜
      print(move)
      return move
    # 如果计算机在该棋位行棋不能获胜,
    board[move] = EMPTY # 悔棋,更换下一个合法棋位
  
  # 阻止玩家获胜
  for move in legal_moves(board): # 合法的行棋位置列表
    board[move] = human # 更新棋盘
    if winner(board) == human:
      # 在该棋位玩家行棋后将获胜
      print(move)
      return move
    # 玩家不能获胜,不行棋至此
    board[move] = EMPTY

  # 没有能使行棋双方立决胜负的棋位,从优先棋位选择合法行棋位置
  for move in BEST_MOVES:
    if move in legal_moves(board):
      print(move)
      return move


def next_turn(turn):
  '''切换行棋方'''
  if turn == X:
    return O
  else:
    return X

  
def congrat_winner(the_winner, computer, human):
  '''向获胜方表示祝贺或声明平局'''
  if the_winner != TIE:
    print(the_winner, '祝贺你!\n')
  else:
    print('平局。。。\n')

  if the_winner == computer:
    print('如我所料,我又胜了。\n这是否能说明计算机在给方面都优于人类呢?')

  elif the_winner == human:
    print('真是匪夷所思,你没捣鬼吧?人类怎么会胜? \n不会有下次了。' )

  elif the_winner == TIE:
    print('你很厉害嘛,能跟计算机打成平手。')

3、定义主函数

def main():
  display_instruct() # 显示游戏操作指南
  computer, human = pieces() # 决定谁先行棋
  turn = X # 先行棋方执子 X
  board = new_board() # 创建空棋盘
  display_board(board) # 显示棋盘

  while not winner(board): 
    # 判定结果,在没有获胜方且不是平局时进入循环
    if turn == human:
      # 轮到玩家行棋,玩家行棋
      move = human_move(board, human) # 玩家的行棋位置
      board[move] = human # 更新棋盘
    else:
      # 轮到电脑行棋
      move = computer_move(board, computer, human) # 电脑的行棋位置
      board[move] = computer # 更新棋盘
    display_board(board) # 显示更新后的棋盘
    turn = next_turn(turn) # 切换行棋方

  the_winner = winner(board) # 判定获胜者,返回获胜方的执子,平局返回 None
  congrat_winner(the_winner, computer, human) # 向获胜方表示祝贺或声明是平局

4、调用主函数,启动程序

main()
input('\n\n按回车键退出程序。') # 等待用户

在 jupyter 中演练如下:

基于python纯函数实现井字棋游戏

基于python纯函数实现井字棋游戏

基于python纯函数实现井字棋游戏基于python纯函数实现井字棋游戏

基于python纯函数实现井字棋游戏

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
初步认识Python中的列表与位运算符
Oct 12 Python
举例讲解Python编程中对线程锁的使用
Jul 12 Python
win系统下为Python3.5安装flask-mongoengine 库
Dec 20 Python
使用XML库的方式,实现RPC通信的方法(推荐)
Jun 14 Python
Python2.7+pytesser实现简单验证码的识别方法
Dec 29 Python
Django中的Signal代码详解
Feb 05 Python
使用Python写一个小游戏
Apr 02 Python
numpy给array增加维度np.newaxis的实例
Nov 01 Python
python使用Pandas库提升项目的运行速度过程详解
Jul 12 Python
Python字符串和正则表达式中的反斜杠('\')问题详解
Sep 03 Python
Python多线程Threading、子线程与守护线程实例详解
Mar 24 Python
python的链表基础知识点
Sep 13 Python
Python实现读取并写入Excel文件过程解析
May 27 #Python
Python正则表达式如何匹配中文
May 27 #Python
使用python创建Excel工作簿及工作表过程图解
May 27 #Python
Python实现疫情通定时自动填写功能(附代码)
May 27 #Python
Python unittest单元测试openpyxl实现过程解析
May 27 #Python
python实现爱奇艺登陆密码RSA加密的方法示例详解
May 27 #Python
python如何求100以内的素数
May 27 #Python
You might like
使用php shell命令合并图片的代码
2011/06/23 PHP
javascript 函数式编程
2007/08/16 Javascript
javascript一些不错的函数脚本代码
2008/09/10 Javascript
js和as的稳定传值问题解决
2013/07/14 Javascript
javascript实现控制文字大中小显示
2015/04/28 Javascript
老生常谈Javascript中的原型和this指针
2016/10/09 Javascript
JavaScript数据结构中栈的应用之表达式求值问题详解
2017/04/11 Javascript
JS实现中英文混合文字溢出友好截取功能
2018/08/06 Javascript
Vue组件教程之Toast(Vue.extend 方式)详解
2019/01/27 Javascript
详解vue的双向绑定原理及实现
2019/05/05 Javascript
[50:21]Liquid vs Winstrike 2018国际邀请赛小组赛BO2 第二场
2018/08/19 DOTA
Python存取XML的常见方法实例分析
2017/03/21 Python
python 实现上传图片并预览的3种方法(推荐)
2017/07/14 Python
python实现浪漫的烟花秀
2019/01/30 Python
selenium+python自动化测试环境搭建步骤
2019/06/03 Python
Python内存管理实例分析
2019/07/10 Python
Python 离线工作环境搭建的方法步骤
2019/07/29 Python
Django CBV与FBV原理及实例详解
2019/08/12 Python
Python3 pandas 操作列表实例详解
2019/09/23 Python
python实现KNN分类算法
2019/10/16 Python
python 实现一个反向单位矩阵示例
2019/11/29 Python
使用Python爬虫库requests发送请求、传递URL参数、定制headers
2020/01/25 Python
Python如何使用OS模块调用cmd
2020/02/27 Python
Python tkinter布局与按钮间距设置方式
2020/03/04 Python
windows10环境下用anaconda和VScode配置的图文教程
2020/03/30 Python
Jupyter安装链接aconda实现过程图解
2020/11/02 Python
Mountain Warehouse波兰官方网站:英国户外品牌
2019/08/29 全球购物
求职简历自荐信
2013/10/20 职场文书
大学毕业后的十年规划
2014/01/07 职场文书
网络信息安全承诺书
2014/03/26 职场文书
班级出游活动计划书
2014/08/15 职场文书
村主任个人对照检查材料
2014/10/01 职场文书
2015年小班保育员工作总结
2015/05/27 职场文书
同事离别感言
2015/08/04 职场文书
房屋转让协议书(标准范本)
2016/03/21 职场文书
Go使用协程交替打印字符
2021/04/29 Golang