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+django实现文件上传
Jan 17 Python
LRUCache的实现原理及利用python实现的方法
Nov 21 Python
利用Python找出序列中出现最多的元素示例代码
Dec 08 Python
使用pandas read_table读取csv文件的方法
Jul 04 Python
用python实现k近邻算法的示例代码
Sep 06 Python
python utc datetime转换为时间戳的方法
Jan 15 Python
使用Python自动化破解自定义字体混淆信息的方法实例
Feb 13 Python
使用python socket分发大文件的实现方法
Jul 08 Python
python如何建立全零数组
Jul 19 Python
基于python图书馆管理系统设计实例详解
Aug 05 Python
Python基于callable函数检测对象是否可被调用
Oct 16 Python
用Python将库打包发布到pypi
Apr 13 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调用MsSQL Server 2012存储过程获取多结果集(包含output参数)的详解
2013/07/03 PHP
PHP包含文件函数include、include_once、require、require_once区别总结
2014/04/05 PHP
基于php的微信公众平台开发入门实例
2015/04/15 PHP
php比较两个字符串长度的方法
2015/07/13 PHP
PHP命名空间namespace的定义方法详解
2017/03/29 PHP
利用PHP获取访客IP、地区位置、浏览器及来源页面等信息
2017/06/27 PHP
原生JS实现Ajax通过GET方式与PHP进行交互操作示例
2018/05/12 PHP
PHP的new static和new self的区别与使用
2019/11/27 PHP
非常好的js代码
2006/06/27 Javascript
javascript递归回溯法解八皇后问题
2015/04/22 Javascript
JavaScript必知必会(七)js对象继承
2016/06/08 Javascript
分享bootstrap学习笔记心得(组件及其属性)
2017/01/11 Javascript
node.js 中间件express-session使用详解
2017/05/20 Javascript
通过jquery获取上传文件名称、类型和大小的实现代码
2018/04/19 jQuery
详解ES6中的Map与Set集合
2019/03/22 Javascript
微信小程序用户授权弹窗 拒绝时引导用户重新授权实现
2019/07/29 Javascript
封装一下vue中的axios示例代码详解
2020/02/16 Javascript
Node 模块原理与用法详解
2020/05/13 Javascript
python抓取网页时字符集转换问题处理方案分享
2014/06/19 Python
Python基类函数的重载与调用实例分析
2015/01/12 Python
在Python中操作列表之list.extend()方法的使用
2015/05/20 Python
Python遍历目录中的所有文件的方法
2016/07/08 Python
python实现程序重启和系统重启方式
2020/04/16 Python
关于 HTML5 的七个传说小结
2012/04/12 HTML / CSS
Omio意大利:全欧洲低价大巴、火车和航班搜索和比价
2017/12/02 全球购物
俄罗斯运动、健康和美容产品在线商店:Lactomin.ru
2020/07/23 全球购物
事业单位接收函
2014/01/10 职场文书
烹调加工管理制度
2014/02/04 职场文书
大学生学习2014全国两会心得体会
2014/03/13 职场文书
综合内勤岗位职责
2014/04/14 职场文书
小学趣味运动会加油稿
2014/09/25 职场文书
四年级数学教学反思
2016/02/16 职场文书
Python数据分析之绘图和可视化详解
2021/06/02 Python
MySQL 亿级数据导入导出及迁移笔记
2021/06/18 MySQL
Mysql中的触发器定义及语法介绍
2022/06/25 MySQL
Python使用pandas导入xlsx格式的excel文件内容操作代码
2022/12/24 Python