目录

board

game

player


board 

class Board(object):"""棋盘类"""def __init__(self):self.board_data = [" "] * 9  # 棋盘数据self.movable_list = list(range(9))  # 可移动列表def show_board(self, show_index=False):"""显示棋盘:param show_index: True 表示显示索引 / False 表示显示数据"""for i in (0, 3, 6):print("       |       |")if show_index:print("   %d   |   %d   |   %d" % (i, i + 1, i + 2))else:print("   %s   |   %s   |   %s" % (self.board_data[i],self.board_data[i + 1],self.board_data[i + 2]))print("       |       |")if i != 6:print("-" * 23)def move_down(self, index, chess):"""在指定位置落子:param index: 列表索引:param chess: 棋子类型 X 或 O"""# 1. 判断 index 是否在可移动列表中if index not in self.movable_list:print("%d 位置不允许落子" % index)return# 2. 修改棋盘数据self.board_data[index] = chess# 3. 修改可移动列表self.movable_list.remove(index)def is_draw(self):"""是否平局"""return not self.movable_listdef is_win(self, chess, ai_index=-1):"""是否胜利:param chess: 玩家的棋子:param ai_index: 预判索引,-1 直接判断当前棋盘数据"""# 1. 定义检查方向列表check_dirs = [[0, 1, 2], [3, 4, 5], [6, 7, 8],[0, 3, 6], [1, 4, 7], [2, 5, 8],[0, 4, 8], [2, 4, 6]]# 2. 定义局部变量记录棋盘数据副本data = self.board_data.copy()# 判断是否预判胜利if ai_index > 0:data[ai_index] = chess# 3. 遍历检查方向列表判断是否胜利for item in check_dirs:if (data[item[0]] == chess anddata[item[1]] == chessand data[item[2]] == chess):return Truereturn Falsedef reset_board(self):"""重置棋盘"""# 1. 清空可移动列表数据self.movable_list.clear()# 2. 重置数据for i in range(9):self.board_data[i] = " "self.movable_list.append(i)if __name__ == '__main__':# 1. 测试初始化board = Board()print(board.board_data)print(board.movable_list)# 2. 显示棋盘print("--- 显示棋盘" + "-" * 50)board.show_board(True)  # 显示索引print("-" * 50)board.show_board()  # 显示数据# 3. 测试落子print("--- 测试落子" + "-" * 50)board.move_down(0, "X")board.show_board()print(board.movable_list)board.move_down(0, "X")  # 测试在已有棋子的位置落子# 4. 判断平局# print("--- 判断平局" + "-" * 50)# print("是否平局 %d" % board.is_draw())# board.movable_list.clear()  # 清空可移动索引列表# print("是否平局 %d" % board.is_draw())# 5. 判断胜利print("---判断胜利" + "-" * 50)print("是否胜利 %d" % board.is_win("X"))board.move_down(0, "X")board.move_down(1, "X")board.move_down(2, "X")board.show_board()print("是否胜利 %d" % board.is_win("X"))# 6. 测试重置棋盘数据print("--- 重置棋盘" + "-" * 50)board.reset_board()board.show_board()print(board.movable_list)
import random
import board
import playerclass Game(object):"""游戏类"""def __init__(self):self.chess_board = board.Board()  # 棋盘对象self.human = player.Player("玩家")  # 人类玩家对象self.computer = player.AIPlayer("电脑")  # 电脑玩家对象def random_player(self):"""随机先手玩家:return: 落子先后顺序的玩家元组"""# 随机到 1 表示玩家先手if random.randint(0, 1) == 1:players = (self.human, self.computer)else:players = (self.computer, self.human)# 设置玩家棋子players[0].chess = "X"players[1].chess = "O"print("根据随机抽取结果 %s 先行" % players[0].name)return playersdef play_round(self):"""一轮完整对局"""# 1. 显示棋盘落子位置self.chess_board.show_board(True)# 2. 随机决定先手current_player, next_player = self.random_player()# 3. 两个玩家轮流落子while True:# 下子方落子current_player.move(self.chess_board)# 显示落子结果self.chess_board.show_board()# 是否胜利?if self.chess_board.is_win(current_player.chess):print("%s 战胜 %s" % (current_player.name, next_player.name))current_player.score += 1break# 是否平局if self.chess_board.is_draw():print("%s 和 %s 战成平局" % (current_player.name, next_player.name))break# 交换落子方current_player, next_player = next_player, current_player# 4. 显示比分print("[%s] 对战 [%s] 比分是 %d : %d" % (self.human.name,self.computer.name,self.human.score,self.computer.score))def start(self):"""循环开始对局"""while True:# 一轮完整对局self.play_round()# 询问是否继续is_continue = input("是否再来一盘(Y/N)?").upper()# 判断玩家输入if is_continue != "Y":break# 重置棋盘数据self.chess_board.reset_board()if __name__ == '__main__':Game().start()

player

import random
import boardclass Player(object):"""玩家类"""def __init__(self, name):self.name = name  # 姓名self.score = 0  # 成绩self.chess = None  # 棋子def move(self, chess_board):"""在棋盘上落子:param chess_board:"""# 1. 由用户输入要落子索引index = -1while index not in chess_board.movable_list:try:index = int(input("请 “%s” 输入落子位置 %s:" %(self.name, chess_board.movable_list)))except ValueError:pass# 2. 在指定位置落子chess_board.move_down(index, self.chess)class AIPlayer(Player):"""智能玩家"""def move(self, chess_board):"""在棋盘上落子:param chess_board:"""print("%s 正在思考落子位置..." % self.name)# 1. 查找我方必胜落子位置for index in chess_board.movable_list:if chess_board.is_win(self.chess, index):print("走在 %d 位置必胜!!!" % index)chess_board.move_down(index, self.chess)return# 2. 查找地方必胜落子位置-我方必救位置other_chess = "O" if self.chess == "X" else "X"for index in chess_board.movable_list:if chess_board.is_win(other_chess, index):print("敌人走在 %d 位置必输,火速堵上!" % index)chess_board.move_down(index, self.chess)return# 3. 根据子力价值选择落子位置index = -1# 没有落子的角位置列表corners = list(set([0, 2, 6, 8]).intersection(chess_board.movable_list))# 没有落子的边位置列表edges = list(set([1, 3, 5, 7]).intersection(chess_board.movable_list))if 4 in chess_board.movable_list:index = 4elif corners:index = random.choice(corners)elif edges:index = random.choice(edges)# 在指定位置落子chess_board.move_down(index, self.chess)if __name__ == '__main__':# 1. 创建棋盘对象chess_board = board.Board()# 2. 创建玩家对象human = Player("玩家")human.chess = "X"# 3. 玩家在棋盘上循环落子,直到玩家胜利while not chess_board.is_win(human.chess):human.move(chess_board)# 显示棋盘chess_board.show_board()

python实例:井字棋相关推荐

  1. python实现井字棋

    参考学习:Python实现井字棋游戏 闲扯 井字棋(Tic-Tac-Toe),初高中进行打发时间的一种画x画o的游戏,3*3的格子组成,一方把行列斜行连成相同的就算获胜. 那么怎么利用进行人机对弈这种 ...

  2. python编写井字棋_编写井字游戏

    python编写井字棋 Programming computer games may be the most technically challenging (and possibly the bes ...

  3. python模拟井字棋

    一组井字棋游戏的python实现. 创建一个三横三竖的棋盘,以小键盘数字1-9代表棋盘中的位置,玩家分别执#和0棋子.以连城一条线为胜利. 运行代码显示结果如下: 代码如下: import copyd ...

  4. php井字游戏,python实现井字棋游戏

    #本游戏python3.4.0下编写调试,只能在windows下运行. import random import subprocess import time #定义函数 def draw_board ...

  5. python写井字棋_python 游戏(井字棋)

    1. 游戏思路和流程图 实现功能,现实生活中的井字棋玩法 游戏流程图SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠. 2. 使用模块和游戏提示 impor ...

  6. python写井字棋_python实现简单井字棋游戏

    #!/usr/bin/env python3 # -*- coding:utf-8 -*- u''' Created on 2019年4月13日 @author: wuluo ''' author = ...

  7. python井字棋游戏代码_python实现井字棋游戏

    python实现井字棋游戏 来源:中文源码网    浏览: 次    日期:2018年9月2日 [下载文档:  python实现井字棋游戏.txt ] (友情提示:右键点上行txt文档名->目标 ...

  8. python井字棋_python实现井字棋小游戏

    本文为大家分享了python实现井字棋小游戏,供大家参考,具体内容如下 周五晚上上了python的选修课,本来以为老师是从python的基础语法开始的,没想到是从turtle画图开始,正好补上了我以前 ...

  9. python井字棋。分与人机和朋友下的那种

    python井字棋快来看看孩子的头发 怎么用python做井字棋游戏,废话不多说上代码! 相关说明 怎么用python做井字棋游戏,废话不多说上代码! 觉得有帮助送我上去!!!!!!!!!!!!!!! ...

  10. python井字棋小游戏代码_python实现井字棋小游戏

    本文为大家分享了python实现井字棋小游戏,供大家参考,具体内容如下 周五晚上上了python的选修课,本来以为老师是从python的基础语法开始的,没想到是从turtle画图开始,正好补上了我以前 ...

最新文章

  1. Javascript鼠标滚轮事件兼容写法
  2. 在服务器托管中对流量和带宽进行限制
  3. 链表系列之单链表——使用单链表实现大整数相加
  4. sqlserver 创建对某个存储过程执行情况的跟踪
  5. Cloudera Manager内部结构、功能包括配置文件、目录位置等
  6. linux系统lsmod命令,linux lsmod命令 及相关信息
  7. 网站快速成型_我的老板对快速成型有什么期望?
  8. 如何基于大数据及AI平台实现业务系统实时化?
  9. 扫描线三巨头 hdu1928hdu 1255 hdu 1542 [POJ 1151]
  10. python直线检测_opencv+python 开操作进行直线检测
  11. 模型加速——卷积通道裁剪的学习笔记
  12. matlab实现图像的左右翻转
  13. 安装 PHP memcached 扩展遇到的3个问题
  14. ubuntu linux 软件安装位置,ubuntu查看软件安装位置
  15. Unity做MMD(一)资源处理
  16. [初学笔记] tic toc 计算程序运行时间
  17. 迅雷Beta来了,这软件太实用了,磁力随心下
  18. 百度AI开放平台 UNIT平台开发在线客服 借助百度的人工智能如何开发一个在线客服系统...
  19. gain在matlab里什么意思,gain gray是什么意思
  20. Android Studio download fastutil-7.2.0.jar下载依赖包超时问题

热门文章

  1. Charles手机端抓包,抓取小说软件整本小说的示例
  2. Spring MVC 406
  3. 配置远程GPU服务器
  4. 软件测试基础知识汇总(问答篇)
  5. php禁用gopher协议,SSRF攻击-运用gopher协议构造POST包--emmmm(http://10.112.68.215:10004/index.php?action=login)...
  6. veu中时间转换----element-UI上Date-Picker时间控件
  7. 程序员常用十大算法(四):KMP算法 与 暴力匹配算法 解决字符串匹配问题
  8. ExifTool文件鉴定器
  9. 八月冲刺月紧张记录(目标400+
  10. Excel中杂乱的图片,一键就可以让它们对齐行