python编写五子棋游戏


Posted in Python onMay 25, 2021

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

游戏代码及部分注释

import pygame        #导入pygame游戏模块
import time           #调用time库
import sys
from pygame.locals import *

initChessList = []          #保存的是棋盘坐标
initRole = 1                #1:代表白棋; 2:代表黑棋
resultFlag = 0              #结果标志

class StornPoint():
    def __init__(self,x,y,value):
        '''
        :param x: 代表x轴坐标
        :param y: 代表y轴坐标
        :param value: 当前坐标点的棋子:0:没有棋子 1:白子 2:黑子
        '''
        self.x = x            #初始化成员变量
        self.y = y
        self.value = value

def initChessSquare(x,y):     #初始化棋盘
    for i in range(15):       # 每一行的交叉点坐标
        rowlist = []
        for j in range(15):   # 每一列的交叉点坐标
            pointX = x+ j*40
            pointY = y+ i*40
            sp = StornPoint(pointX,pointY,0)
            rowlist.append(sp)
        initChessList.append(rowlist)

def eventHander():            #监听各种事件
    for event in pygame.event.get():
        global initRole
        if event.type == QUIT:#事件类型为退出时
            pygame.quit()
            sys.exit()
        if event.type == MOUSEBUTTONDOWN: #当点击鼠标时
            x,y = pygame.mouse.get_pos()  #获取点击鼠标的位置坐标
            i=0
            j=0
            for temp in initChessList:
                for point in temp:
                    if x>=point.x-10 and x<=point.x+10 and y>=point.y-10 and y<=point.y+10:
                        if point.value == 0 and initRole == 1:   #当棋盘位置为空;棋子类型为白棋
                            point.value = 1             #鼠标点击时,棋子为白棋
                            judgeResult(i,j,1)
                            initRole = 2                #切换角色
                        elif point.value == 0 and initRole ==2:  #当棋盘位置为空;棋子类型为黑棋
                            point.value = 2             #鼠标点击时,棋子为黑棋
                            judgeResult(i,j,2)
                            initRole = 1                #切换角色
                        break
                    j+=1
                i+=1
                j=0

def judgeResult(i,j,value):   #横向判断
    global resultFlag
    flag = False
    for  x in  range(j - 4, j + 5):  # 横向有没有出现5连(在边缘依次逐一遍历,是否五个棋子的类型一样)
        if x >= 0 and x + 4 < 15 :
            if initChessList[i][x].value == value and \
                initChessList[i][x + 1].value == value and \
                initChessList[i][x + 2].value == value and \
                initChessList[i][x + 3].value == value and \
                initChessList[i][x + 4].value == value :
                flag = True
                break
                pass
    for x in range(i - 4, i + 5):  # 纵向有没有出现5连(在边缘依次逐一遍历,是否五个棋子的类型一样)
        if x >= 0 and x + 4 < 15:
            if initChessList[x][j].value == value and \
                    initChessList[x + 1][j].value == value and \
                    initChessList[x + 2][j].value == value and \
                    initChessList[x + 3][j].value == value and \
                    initChessList[x + 4][j].value == value:
                flag = True
                break
                pass

    # 先判断东北方向的对角下输赢 x 列轴, y是行轴 , i 是行 j 是列(右斜向)(在边缘依次逐一遍历,是否五个棋子的类型一样)
    for x, y in zip(range(j + 4, j - 5, -1), range(i - 4, i + 5)):
        if x >= 0 and x + 4 < 15 and y + 4 >= 0 and y < 15:
            if initChessList[y][x].value == value and \
                    initChessList[y - 1][x + 1].value == value and \
                    initChessList[y - 2][x + 2].value == value and \
                    initChessList[y - 3][x + 3].value == value and \
                    initChessList[y - 4][x + 4].value == value:
                flag = True

    # 2、判断西北方向的对角下输赢 x 列轴, y是行轴 , i 是行 j 是列(左斜向)(在边缘依次逐一遍历,是否五个棋子的类型一样)
    for x, y in zip(range(j - 4, j + 5), range(i - 4, i + 5)):
        if x >= 0 and x + 4 < 15 and y >= 0 and y + 4 < 15:
            if initChessList[y][x].value == value and \
                    initChessList[y + 1][x + 1].value == value and \
                    initChessList[y + 2][x + 2].value == value and \
                    initChessList[y + 3][x + 3].value == value and \
                    initChessList[y + 4][x + 4].value == value:
                flag = True


    if flag:               #如果条件成立,证明五子连珠
        resultFlag = value #获取成立的棋子颜色
        print("白棋赢" if value ==1 else "黑棋赢")

# 加载素材
def main():
    global initChessList,resultFlag
    initChessSquare(27,27)
    pygame.init()     # 初始化游戏环境
    screen = pygame.display.set_mode((620,620),0,0)          # 创建游戏窗口 # 第一个参数是元组:窗口的长和宽
    pygame.display.set_caption("陈晓超五子棋")                # 添加游戏标题
    background = pygame.image.load("D:/cxc/4.png")          #加载背景图片
    whiteStorn = pygame.image.load("D:/cxc/2.png") #加载白棋图片
    blackStorn = pygame.image.load("D:/cxc/1.png") #加载黑棋图片
    resultStorn = pygame.image.load("D:/cxc/3.png")#加载 赢 时的图片
    rect = blackStorn.get_rect()

    while True:
        screen.blit(background,(0,0))
        for temp in initChessList:
            for point in temp:
                if point.value == 1:          #当棋子类型为1时,绘制白棋
                    screen.blit(whiteStorn,(point.x-18,point.y-18))
                elif point.value == 2:        #当棋子类型为2时,绘制黑棋
                    screen.blit(blackStorn,(point.x-18,point.y-18))

        if resultFlag >0:
            initChessList = []                 # 清空棋盘
            initChessSquare(27,27)             # 重新初始化棋盘
            screen.blit(resultStorn,(200,200)) #绘制获胜时的图片
        pygame.display.update()                #更新视图

        if resultFlag >0:
            time.sleep(3)
            resultFlag = 0                     #置空之前的获胜结果
        eventHander()                          #调用之前定义的事件函数
if __name__ == '__main__':
    main()        #调用主函数绘制窗口
    pass

运行后就会出现游戏的窗口,像这样:

python编写五子棋游戏

我们可以任意的在棋盘上落子,像这样:

python编写五子棋游戏

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

Python 相关文章推荐
python调用新浪微博API项目实践
Jul 28 Python
python实现查询IP地址所在地
Mar 29 Python
在Python中操作字典之fromkeys()方法的使用
May 21 Python
python结合API实现即时天气信息
Jan 19 Python
django 2.0更新的10条注意事项总结
Jan 05 Python
Python操作Sql Server 2008数据库的方法详解
May 17 Python
Python 输入一个数字判断成绩分数等级的方法
Nov 15 Python
python matplotlib库绘制散点图例题解析
Aug 10 Python
python科学计算之scipy——optimize用法
Nov 25 Python
基于django和dropzone.js实现上传文件
Nov 24 Python
Linux系统下升级pip的完整步骤
Jan 31 Python
Python 装饰器(decorator)常用的创建方式及解析
Apr 24 Python
浅谈python数据类型及其操作
对Keras自带Loss Function的深入研究
May 25 #Python
pytorch中的model=model.to(device)使用说明
May 24 #Python
解决pytorch-gpu 安装失败的记录
May 24 #Python
如何解决.cuda()加载用时很长的问题
一劳永逸彻底解决pip install慢的办法
May 24 #Python
Django实现翻页的示例代码
May 24 #Python
You might like
PHP 类相关函数的使用详解
2013/05/10 PHP
PHP 使用redis简单示例分享
2015/03/05 PHP
php字符串按照单词进行反转的方法
2015/03/14 PHP
php从字符串创建函数的方法
2015/03/16 PHP
教你在PHPStorm中配置Xdebug
2015/07/27 PHP
PHP实现类似题库抽题效果
2018/08/16 PHP
Laravel自定义 封装便捷返回Json数据格式的引用方法
2019/09/29 PHP
js ondocumentready onmouseover onclick onmouseout 样式
2010/07/22 Javascript
如何判断鼠标是否在DIV的区域内
2013/11/13 Javascript
如何动态的导入js文件具体该怎么实现
2014/01/14 Javascript
jQuery检查事件是否触发的方法
2015/06/26 Javascript
基于OL2实现百度地图ABCD marker的效果
2015/10/01 Javascript
js实现仿qq消息的弹出窗效果
2016/01/06 Javascript
Bootstrap基本样式学习笔记之标签(5)
2016/12/07 Javascript
fullPage.js和CSS3实现全屏滚动效果
2017/05/05 Javascript
用javascript获取任意颜色的更亮或更暗颜色值示例代码
2017/07/21 Javascript
第一个Vue插件从封装到发布
2017/11/22 Javascript
基于JavaScript实现简单的音频播放功能
2018/01/07 Javascript
Vue中使用sass实现换肤功能
2018/09/07 Javascript
JS实现的获取银行卡号归属地及银行卡类型操作示例
2019/01/08 Javascript
微信小程序云开发(数据库)详解
2019/05/17 Javascript
使用p5.js临摹动态图形
2019/10/23 Javascript
swiper实现异形轮播效果
2019/11/28 Javascript
DWR内存兼容及无法调用问题解决方案
2020/10/16 Javascript
Python中pillow知识点学习
2018/04/30 Python
Python清空文件并替换内容的实例
2018/10/22 Python
使用Python串口实时显示数据并绘图的例子
2019/12/26 Python
Pycharm打开已有项目配置python环境的方法
2020/07/03 Python
荷兰多品牌网上鞋店:Stoute Schoenen
2017/08/24 全球购物
如何在Oracle中查看各个表、表空间占用空间的大小
2015/10/31 面试题
EJB3推出JPA的原因
2013/10/16 面试题
英语专业个人求职信范文
2014/02/01 职场文书
基督教婚礼主持词
2014/03/14 职场文书
医院搬迁方案
2014/06/14 职场文书
党员贯彻十八大精神思想汇报范文
2014/10/25 职场文书
Python OpenCV 彩色与灰度图像的转换实现
2021/06/05 Python