python实现简单的五子棋游戏


Posted in Python onSeptember 01, 2020

本文实例为大家分享了python实现五子棋游戏的具体代码,供大家参考,具体内容如下

# -*- coding:utf-8 -*-
# @Time: 2017/8/29 0029 10:14
# @Author: assasin
# @Email: assasin0308@sina.com
 
from tkinter import *
import math
 
class chessBoard():
  def __init__(self):
    # 创建一个tk对象,窗口
    self.window = Tk()
    # 窗口名称
    self.window.title('五子棋游戏')
    # 窗口大小
    self.window.geometry('660x470')
    # 设置窗口不可缩放
    self.window.resizable(0,0)
    # 定义窗口的画布
    self.canvas = Canvas(self.window, bg="#EEE8AC", width=470, height=470)
    # 画出画布内容
    self.paint_board()
    # 定义画布所在的网格
    self.canvas.grid(row=0, column=0)
 
  def paint_board(self):
    # 画横线
    for row in range(0, 15):
      if row == 0 or row == 14:
        self.canvas.create_line(25, 25 + row * 30, 25 + 14 * 30, 25 + row * 30, width=2)
    else:
      self.canvas.create_line(25, 25 + row * 30, 25 + 14 * 30, 25 + row * 30, width=1)
 
    # 画竖线
    for column in range(0, 15):
      if column == 0 or column == 14:
        self.canvas.create_line(25 + column * 30, 25, 25 + column * 30, 25 + 14 * 30, width=2)
    else:
      self.canvas.create_line(25 + column * 30, 25, 25 + column * 30, 25 + 14 * 30, width=1)
 
    # 画圆
    self.canvas.create_oval(112, 112, 118, 118, fill="black")
    self.canvas.create_oval(352, 112, 358, 118, fill="black")
    self.canvas.create_oval(112, 352, 118, 358, fill="black")
    self.canvas.create_oval(232, 232, 238, 238, fill="black")
    self.canvas.create_oval(352, 352, 358, 358, fill="black")
 
 
 
 
#定义五子棋游戏类
#0为黑子 , 1为白子 , 2为空位
class Gobang() :
  #初始化
  def __init__(self) :
    self.board = chessBoard()
    self.game_print = StringVar()
    self.game_print.set("")
    # 16*16的二维列表,保证不会out of index
    self.db = [([2] * 16) for i in range(16)]
    # 悔棋用的顺序列表
    self.order = []
    # 棋子颜色
    self.color_count = 0
    self.color = 'black'
    # 清空与赢的初始化,已赢为1,已清空为1
    self.flag_win = 1
    self.flag_empty = 1
    self.options()
 
    # 黑白互换
  def change_color(self):
    self.color_count = (self.color_count + 1) % 2
    if self.color_count == 0:
      self.color = "black"
    elif self.color_count == 1:
      self.color = "white"
 
  # 落子
  def chess_moving(self,event):
    # 不点击“开始”与“清空”无法再次开始落子
    if self.flag_win == 1 or self.flag_empty == 0:
      return
    # 坐标转化为下标
    x, y = event.x - 25, event.y - 25
    x = round(x / 30)
    y = round(y / 30)
    # 点击位置没用落子,且没有在棋盘线外,可以落子
    while self.db[y][x] == 2 and self.limit_boarder(y, x):
      self.db[y][x] = self.color_count
    self.order.append(x + 15 * y)
    self.board.canvas.create_oval(25 + 30 * x - 12, 25 + 30 * y - 12, 25 + 30 * x + 12, 25 + 30 * y + 12,fill=self.color, tags="chessman")
    if self.game_win(y, x, self.color_count):
      print(self.color, "获胜")
      self.game_print.set(self.color + "获胜")
    else:
      self.change_color()
      self.game_print.set("请" + self.color + "落子")
 
  # 保证棋子落在棋盘上
  def limit_boarder(self, y, x):
    if x < 0 or x > 14 or y < 0 or y > 14:
      return False
    else:
      return True
 
  # 计算连子的数目,并返回最大连子数目
  def chessman_count(self, y, x, color_count):
    count1, count2, count3, count4 = 1, 1, 1, 1
    # 横计算
    for i in range(-1, -5, -1):
      if self.db[y][x + i] == color_count:
        count1 += 1
      else:
        break
 
    for i in range(1, 5, 1):
      if self.db[y][x + i] == color_count:
        count1 += 1
      else:
        break
    # 竖计算
    for i in range(-1, -5, -1):
      if self.db[y + i][x] == color_count:
        count2 += 1
      else:
        break
    for i in range(1, 5, 1):
      if self.db[y + i][x] == color_count:
        count2 += 1
      else:
        break
    # /计算
    for i in range(-1, -5, -1):
      if self.db[y + i][x + i] == color_count:
        count3 += 1
      else:
        break
    for i in range(1, 5, 1):
      if self.db[y + i][x + i] == color_count:
        count3 += 1
      else:
        break
 
    # \计算
    for i in range(-1, -5, -1):
      if self.db[y + i][x - i] == color_count:
        count4 += 1
      else:
        break
    for i in range(1, 5, 1):
      if self.db[y + i][x - i] == color_count:
        count4 += 1
      else:
        break
 
    return max(count1, count2, count3, count4)
 
 
  # 判断输赢
  def game_win(self , y , x , color_count ):
    if self.chessman_count(y, x, color_count) >= 5:
      self.flag_win = 1
      self.flag_empty = 0
      return True
    else:
      return False
 
  #悔棋,清空棋盘,再画剩下的n-1个棋子
  def withdraw(self):
    if len(self.order) == 0 or self.flag_win == 1:
      return
    self.board.canvas.delete("chessman")
    z = self.order.pop()
    x = z % 15
    y = z // 15
    self.db[y][x] = 2
    self.color_count = 1
    for i in self.order:
      ix = i % 15
    iy = i // 15
    self.change_color()
    self.board.canvas.create_oval(25 + 30 * ix - 12, 25 + 30 * iy - 12, 25 + 30 * ix + 12, 25 + 30 * iy + 12,
                   fill=self.color, tags="chessman")
    self.change_color()
    self.game_print.set("请" + self.color + "落子")
 
  # 清空
  def empty_all(self) :
    self.board.canvas.delete("chessman")
    # 还原初始化
    self.db = [([2] * 16) for i in range(16)]
    self.order = []
    self.color_count = 0
    self.color = 'black'
    self.flag_win = 1
    self.flag_empty = 1
    self.game_print.set("")
 
  #将self.flag_win置0才能在棋盘上落子
  def game_start(self):
    # 没有清空棋子不能置0开始
    if self.flag_empty == 0:
      return
    self.flag_win = 0
    self.game_print.set("请" + self.color + "落子")
 
  def options(self):
    self.board.canvas.bind("<Button-1>", self.chess_moving)
    Label(self.board.window, textvariable=self.game_print, font=("Arial", 20)).place(relx=0, rely=0, x=495, y=200)
    Button(self.board.window, text="开始游戏", command=self.game_start, width=13, font=("Verdana", 12)).place(relx=0,rely=0,x=495,y=15)
    Button(self.board.window, text="我要悔棋", command=self.withdraw, width=13, font=("Verdana", 12)).place(relx=0,rely=0,x=495, y=60)
    Button(self.board.window, text="清空棋局", command=self.empty_all, width=13, font=("Verdana", 12)).place(relx=0,rely=0,x=495,y=105)
    Button(self.board.window, text="结束游戏", command=self.board.window.destroy, width=13, font=("Verdana", 12)).place(relx=0, rely=0, x=495, y=420)
    self.board.window.mainloop()
 
 
if __name__ == '__main__':
  chess_game = Gobang()

更多有趣的经典小游戏实现专题,分享给大家:

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

Python 相关文章推荐
Python读取图片EXIF信息类库介绍和使用实例
Jul 10 Python
Python创建文件和追加文件内容实例
Oct 21 Python
python实现在字符串中查找子字符串的方法
Jul 11 Python
Python实现短网址ShortUrl的Hash运算实例讲解
Aug 10 Python
Python自动化运维之IP地址处理模块详解
Dec 10 Python
完美解决Pycharm无法导入包的问题 Unresolved reference
May 18 Python
解决pandas 作图无法显示中文的问题
May 24 Python
Python数据结构与算法(几种排序)小结
Jun 22 Python
mac系统下Redis安装和使用步骤详解
Jul 09 Python
django2.2安装错误最全的解决方案(小结)
Sep 24 Python
python 日志模块 日志等级设置失效的解决方案
May 26 Python
Python实现钉钉/企业微信自动打卡的示例代码
Feb 02 Python
Pycharm连接gitlab实现过程图解
Sep 01 #Python
pycharm不以pytest方式运行,想要切换回普通模式运行的操作
Sep 01 #Python
python selenium xpath定位操作
Sep 01 #Python
使用python库xlsxwriter库来输出各种xlsx文件的示例
Sep 01 #Python
Python3实现英文字母转换哥特式字体实例代码
Sep 01 #Python
python 解决pycharm运行py文件只有unittest选项的问题
Sep 01 #Python
Python2及Python3如何实现兼容切换
Sep 01 #Python
You might like
PHP运行模式汇总
2016/11/06 PHP
thinkPHP5.0框架引入Traits功能实例分析
2017/03/18 PHP
PHP递归算法的简单实例
2019/02/28 PHP
javascript getElementsByTagName
2011/01/31 Javascript
js/ajax跨越访问-jsonp的原理和实例(javascript和jquery实现代码)
2012/12/27 Javascript
运算符&amp;&amp;的三个不同层次
2013/04/07 Javascript
脚本合并提升javascript性能示例
2014/02/24 Javascript
JavaScript父子窗体间的调用方法
2015/03/31 Javascript
JS实现模拟风力的雪花飘落效果
2015/05/13 Javascript
react-native使用react-navigation进行页面跳转导航的示例
2017/09/07 Javascript
vue做网页开场视频的实例代码
2017/10/20 Javascript
解决easyui日期时间框ie的兼容的问题
2018/03/01 Javascript
JS打印彩色菱形的实例代码
2018/08/15 Javascript
layui-tree实现Ajax异步请求后动态添加节点的方法
2019/09/23 Javascript
Python网页解析利器BeautifulSoup安装使用介绍
2015/03/17 Python
深入浅析python定时杀进程
2016/06/06 Python
Python提取Linux内核源代码的目录结构实现方法
2016/06/24 Python
Python Django使用forms来实现评论功能
2016/08/17 Python
对Django项目中的ORM映射与模糊查询的使用详解
2019/07/18 Python
多版本python的pip 升级后, pip2 pip3 与python版本失配解决方法
2019/09/11 Python
video下autoplay属性无效的解决方法(添加muted属性)
2020/05/19 HTML / CSS
购买瑞典当代设计的腕表和太阳眼镜:TRIWA
2016/10/30 全球购物
校本教研工作制度
2014/01/22 职场文书
技校毕业生个人学习的自我评价
2014/02/21 职场文书
农民工工资承诺书范文
2014/03/31 职场文书
煤矿安全生产责任书
2014/04/15 职场文书
淘宝客服工作职责
2014/07/11 职场文书
大学生党员个人总结
2015/02/13 职场文书
2015年公务员转正工作总结
2015/04/24 职场文书
通知函格式范文
2015/04/27 职场文书
麦田里的守望者读书笔记
2015/06/30 职场文书
酒店开业主持词
2015/07/02 职场文书
关于开学的感想
2015/08/10 职场文书
golang 实现对Map进行键值自定义排序
2021/04/28 Golang
redis不能访问本机真实ip地址的解决方案
2021/07/07 Redis
Redis高并发防止秒杀超卖实战源码解决方案
2021/11/01 Redis