Python tkinter制作单机五子棋游戏


Posted in Python onSeptember 14, 2020

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

以下文章来源于Python家庭,作者Python家庭

实战项目:使用Python编写一个能够完成基本对战的五子棋游戏。面向新手。

程序主要包括两个部分,图形创建与逻辑编写两部分。

程序的运行结果:

Python tkinter制作单机五子棋游戏

样式创建

老规矩,先把用到的包导入进来。

from tkinter import *
import math

然后建立一个样式的类,类名称chessBoard。这里加了很多注释,避免新手看不懂函数的作用,说实话我觉得挺别扭的。

#定义棋盘类
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")

逻辑编写

这里的主要看每个函数的功能就好了。

if __name__ == "__main__":  game = Gobang()

最后,main函数

if __name__ == "__main__":
  game = Gobang()

将以上的所有程序复制粘贴,即为完整的程序了,可以运行。
最后来一个完整程序,一个一个复制粘贴简直不要太麻烦。

from tkinter import *
import math

#定义棋盘类
class chessBoard() :
  def __init__(self) :
    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__":
  game = Gobang()

到此这篇关于Python tkinter制作单机五子棋游戏的文章就介绍到这了,更多相关Python tkinter单机五子制作内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python开发中爬虫使用代理proxy抓取网页的方法示例
Sep 26 Python
Python3用tkinter和PIL实现看图工具
Jun 21 Python
详解Django-auth-ldap 配置方法
Dec 10 Python
python暴力解压rar加密文件过程详解
Jul 05 Python
使用Python脚本zabbix自定义key监控oracle连接状态
Aug 28 Python
python 列表推导式使用详解
Aug 29 Python
django自带调试服务器的使用详解
Aug 29 Python
命令行运行Python脚本时传入参数的三种方式详解
Oct 11 Python
解决python执行较大excel文件openpyxl慢问题
May 15 Python
python 装饰器的实际作用有哪些
Sep 07 Python
详解python的super()的作用和原理
Oct 29 Python
pytorch常用数据类型所占字节数对照表一览
May 17 Python
python安装cx_Oracle和wxPython的方法
Sep 14 #Python
python输入中文的实例方法
Sep 14 #Python
python与js主要区别点总结
Sep 13 #Python
python与c语言的语法有哪些不一样的
Sep 13 #Python
python的链表基础知识点
Sep 13 #Python
python文件排序的方法总结
Sep 13 #Python
python识别验证码的思路及解决方案
Sep 13 #Python
You might like
兼容PHP5的PHP目录管理函数库
2008/07/10 PHP
解决file_get_contents无法请求https连接的方法
2013/12/17 PHP
php常用字符串比较函数实例汇总
2014/11/24 PHP
PHP遍历数组的方法汇总
2015/04/30 PHP
详细解读PHP的Yii框架中登陆功能的实现
2015/08/21 PHP
PHP字符串逆序排列实现方法小结【strrev函数,二分法,循环法,递归法】
2017/01/13 PHP
使用laravel的Eloquent模型如何获取数据库的指定列
2019/10/17 PHP
php连接mysql之mysql_connect()与mysqli_connect()的区别
2020/07/19 PHP
js url传值中文乱码之解决之道
2009/11/20 Javascript
jquery操作checkbox示例分享
2014/07/21 Javascript
JavaScript实现从数组中选出和等于固定值的n个数
2014/09/03 Javascript
JS限制条件补全问题实例分析
2016/12/16 Javascript
基于nodejs 的多页面爬虫实例代码
2017/05/31 NodeJs
JS实现手写parseInt的方法示例
2017/09/24 Javascript
ES6 Iterator接口和for...of循环用法分析
2019/07/31 Javascript
Vue实现星级评价效果实例详解
2019/12/30 Javascript
python中dir函数用法分析
2015/04/17 Python
使用Python的Bottle框架写一个简单的服务接口的示例
2015/08/25 Python
Python+matplotlib实现填充螺旋实例
2018/01/15 Python
pandas 读取各种格式文件的方法
2018/06/22 Python
python networkx 根据图的权重画图实现
2019/07/10 Python
Python-Tkinter Text输入内容在界面显示的实例
2019/07/12 Python
详解程序意外中断自动重启shell脚本(以Python为例)
2019/07/26 Python
Win10+GPU版Pytorch1.1安装的安装步骤
2019/09/27 Python
Python实现一个优先级队列的方法
2020/07/31 Python
python判断元素是否存在的实例方法
2020/09/24 Python
毕业生找工作推荐信
2013/11/21 职场文书
亲子拓展活动方案
2014/02/20 职场文书
GMP办公室主任岗位职责
2014/03/14 职场文书
销售行政专员岗位职责
2014/06/10 职场文书
师德先进个人材料
2014/12/20 职场文书
导游词之永济鹳雀楼
2020/01/16 职场文书
pytorch DataLoader的num_workers参数与设置大小详解
2021/05/28 Python
Python一行代码实现自动发邮件功能
2021/05/30 Python
手把手教你从零开始react+antd搭建项目
2021/06/03 Javascript
如何创建一个创建MySQL数据库中的datetime类型
2022/03/21 MySQL