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 相关文章推荐
C#返回当前系统所有可用驱动器符号的方法
Apr 18 Python
Python数据分析:手把手教你用Pandas生成可视化图表的教程
Dec 15 Python
numpy:np.newaxis 实现将行向量转换成列向量
Nov 30 Python
python实现异常信息堆栈输出到日志文件
Dec 26 Python
python实现简单飞行棋
Feb 06 Python
python标准库os库的函数介绍
Feb 12 Python
在Mac中PyCharm配置python Anaconda环境过程图解
Mar 11 Python
Django Admin设置应用程序及模型顺序方法详解
Apr 01 Python
pycharm 关掉syntax检查操作
Jun 09 Python
解决Python中导入自己写的类,被划红线,但不影响执行的问题
Jul 13 Python
python 如何利用argparse解析命令行参数
Sep 11 Python
Python WebSocket长连接心跳与短连接的示例
Nov 24 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
yii使用activeFileField控件实现上传文件与图片的方法
2015/12/28 PHP
Laravel 框架控制器 Controller原理与用法实例分析
2020/04/14 PHP
jQuery关于导航条背景切换效果实现示例
2013/09/04 Javascript
js中cookie的添加、取值、删除示例代码
2013/10/21 Javascript
20个实用的JavaScript技巧分享
2014/11/28 Javascript
jQuery UI插件自定义confirm确认框的方法
2015/03/20 Javascript
jQuery基于cookie实现的购物车实例分析
2015/12/24 Javascript
详解JavaScript的AngularJS框架中的作用域与数据绑定
2016/03/04 Javascript
详解jQuery简单的表格应用
2016/12/16 Javascript
使用cookie绕过验证码登录的实现代码
2017/10/12 Javascript
layui use 定义js外部引用函数的方法
2019/09/26 Javascript
vue学习笔记之slot插槽用法实例分析
2020/02/29 Javascript
js实现鼠标拖曳效果
2020/12/30 Javascript
[03:51]吞吞映像 每周精彩击杀top10第二弹
2014/06/25 DOTA
python杀死一个线程的方法
2015/09/06 Python
python模块smtplib学习
2018/05/22 Python
在python中只选取列表中某一纵列的方法
2018/11/28 Python
使用Python paramiko模块利用多线程实现ssh并发执行操作
2019/12/05 Python
Python编写一个验证码图片数据标注GUI程序附源码
2019/12/09 Python
Python面向对象程序设计之静态方法、类方法、属性方法原理与用法分析
2020/03/23 Python
使用Python将Exception异常错误堆栈信息写入日志文件
2020/04/08 Python
使用Python防止SQL注入攻击的实现示例
2020/05/21 Python
Python reques接口测试框架实现代码
2020/07/28 Python
python如何调用百度识图api
2020/09/29 Python
Stylenanda中文站:韩国一线网络服装品牌
2016/12/22 全球购物
介绍一下linux的文件系统
2012/03/20 面试题
读书心得体会
2013/12/28 职场文书
担保书怎么写
2014/04/01 职场文书
公司授权委托书
2014/04/04 职场文书
2014年保育员工作总结
2014/12/02 职场文书
课外活动总结
2015/02/04 职场文书
2015年乡镇工作总结范文
2015/04/22 职场文书
2015年财务部年度工作总结
2015/05/19 职场文书
2016年公司中秋节致辞
2015/11/26 职场文书
你会写报告?产品体验报告到底该怎么写?
2019/08/14 职场文书
2020年基层司法所建设情况调研报告
2019/11/30 职场文书