Python开发五子棋游戏【新手必学】
五子棋源码,原创代码,仅供 python 开源项目学习。
目前电脑走法笨笨的,下一期版本会提高电脑算法
ps:另外很多人在学习Python的过程中,往往因为遇问题解决不了或者没好的教程从而导致自己放弃,为此我建了个Python全栈开发交流.裙 :一久武其而而流一思(数字的谐音)转换下可以找到了,里面有最新Python教程项目可拿,不懂的问题有老司机解决哦,一起相互监督共同进步
第二版已发布与另外一篇博文,有兴趣的可以去查看下载。
import pygame
import time
SCREEN_WIDTH=900
SCREEN_HEIGHT=800
BG_COLOR=pygame.Color(200, 200, 200)
Line_COLOR=pygame.Color(255, 255, 200)
TEXT_COLOR=pygame.Color(255, 0, 0)
# 定义颜色
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
class MainGame():
    window = None
    Start_X = 50
    Start_Y = 50
    Line_Span = 40
    Max_X = Start_X + 18 * Line_Span
    Max_Y = Start_Y + 18 * Line_Span
    player1Color = 'B'
    player2Color = 'W'
    overColor = 'S'
    # 1代表玩家1 , 2代表到玩家2  0代表结束
    Putdownflag = player1Color
    ChessmanList = []
    def __init__(self):
        '''初始化'''
    def startGame(self):
        MainGame.window = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
        pygame.display.set_caption("五子棋")
        #初始化
        while True:
            time.sleep(0.1)
            #获取事件
            MainGame.window.fill(BG_COLOR)
            self.drawchChessboard()
            self.bitechessman()
            self.VictoryOrDefeat()
            self.Computerplay()
            self.getEvent()
            pygame.display.update()
            pygame.display.flip()
    def drawchChessboard(self):
        for i in range(0,19):
            x = MainGame.Start_X + i * MainGame.Line_Span
            y = MainGame.Start_Y + i * MainGame.Line_Span
            pygame.draw.line(MainGame.window, BLACK, [x,  MainGame.Start_Y], [x, MainGame.Max_Y], 1)
            pygame.draw.line(MainGame.window, BLACK, [MainGame.Start_X, y], [MainGame.Max_X, y], 1)
    def getEvent(self):
        # 获取所有的事件
        eventList = pygame.event.get()
        for event in eventList:
            if event.type == pygame.QUIT:
                self.endGame()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                mouse_x = pos[0]
                mouse_y = pos[1]
                if (mouse_x > MainGame.Start_X- MainGame.Line_Span/2 and mouse_x < MainGame.Max_X + MainGame.Line_Span / 2) and (mouse_y > MainGame.Start_Y- MainGame.Line_Span/2 and mouse_y < MainGame.Max_Y + MainGame.Line_Span / 2):
                    #print( str(mouse_x) + "" + str(mouse_y))
                    #print(str(MainGame.Putdownflag))
                    if MainGame.Putdownflag != MainGame.player1Color:
                        return
                    click_x = round((mouse_x - MainGame.Start_X) / MainGame.Line_Span)
                    click_y = round((mouse_y - MainGame.Start_Y) / MainGame.Line_Span)
                    click_mod_x = (mouse_x - MainGame.Start_X) % MainGame.Line_Span
                    click_mod_y = (mouse_y - MainGame.Start_Y) % MainGame.Line_Span
                    if abs(click_mod_x-MainGame.Line_Span/2) >=5 and abs(click_mod_y-MainGame.Line_Span/2) >=5:
                        #print("有效点:x="+str(click_x)+" y="+str(click_y))
                        #有效点击点
                        self.putdownchess(MainGame.player1Color, click_x, click_y)
                else:
                    print("out")
    def putdownchess(self, t, x, y):
        flag = False
        for item in  MainGame.ChessmanList:
            if item.x == x and item.y == y:
                flag = True
        if not flag:
            cm = Chessman(t, x, y)
            MainGame.ChessmanList.append(cm)
            MainGame.Putdownflag = MainGame.player2Color
        #print("ChessmanListlen:" + str(len(MainGame.ChessmanList)))
    def bitechessman(self):
        for item in MainGame.ChessmanList:
            item.displaychessman()
    def bureautime(self):
            ''''''
    def Computerplay(self):
        if MainGame.Putdownflag == MainGame.player2Color:
            print("轮到电脑了")
            computer = self.getComputerplaychess()
            if computer==None:
                return
            #print("computer x="+str(computer.x) + "  y="+str(computer.y))
            MainGame.ChessmanList.append(computer)
            MainGame.Putdownflag = MainGame.player1Color
    def getComputerplaychess(self):
        if len(MainGame.ChessmanList) == 0:
            return Chessman(MainGame.player2Color, 9, 9)
        # 进攻
        for item in MainGame.ChessmanList:
            if item.troops == MainGame.player2Color:
                prev_x = item.x - 1
                prev_y = item.y - 1
                next_x = item.x + 1
                next_y = item.y + 1
                print(str(self.calVerticalityCount(item)))
                if self.calVerticalityCount(item) == 4 :
                    if not len(list(filter(lambda x: x.x == prev_x and x.y == item.y,  MainGame.ChessmanList))) :
                        return Chessman(MainGame.player2Color, prev_x, item.y)
                    elif not len(list(filter(lambda x: x.x == item.x+4 and x.y == item.y,  MainGame.ChessmanList))) :
                        print("YYYY  " +str(item.x)+"  "+str(item.y))
                        return Chessman(MainGame.player2Color, item.x+4, item.y)
                if self.calHorizontalCount(item) == 4:
                    if not len(list(filter(lambda x: x.x == item.x and x.y == item.y-1, MainGame.ChessmanList))):
                        return Chessman(MainGame.player2Color, prev_x, item.y-1)
                    elif not len(
                            list(filter(lambda x: x.x == item.x  and x.y == item.y+ 4, MainGame.ChessmanList))):
                        return Chessman(MainGame.player2Color, item.x, item.y+ 4)
        # 防守
        for item in MainGame.ChessmanList:
            if item.troops == MainGame.player1Color:
                next_x = item.x + 1
                next_y = item.y + 1
                if self.calVerticalityCount(item) == 4 :
                    if not len(list(filter(lambda x: x.x == prev_x and x.y == item.y,  MainGame.ChessmanList))) :
                        return Chessman(MainGame.player2Color, prev_x, item.y)
                    elif not len(list(filter(lambda x: x.x == item.x+4 and x.y == item.y,  MainGame.ChessmanList))) :
                        return Chessman(MainGame.player2Color, item.x+4, item.y)
                if self.calHorizontalCount(item) == 4:
                    if not len(list(filter(lambda x: x.x == item.x and x.y == item.y-1, MainGame.ChessmanList))):
                        return Chessman(MainGame.player2Color, prev_x, item.y-1)
                    elif not len(
                            list(filter(lambda x: x.x == item.x  and x.y == item.y+ 4, MainGame.ChessmanList))):
                        return Chessman(MainGame.player2Color, item.x, item.y+ 4)
                if next_x < 19 and len(list(filter(lambda x: x.x == next_x and x.y == item.y,  MainGame.ChessmanList)))==0:
                    return Chessman(MainGame.player2Color, next_x, item.y)
                if next_y < 19 and len(list(filter(lambda x: x.x == item.x and x.y == next_y,  MainGame.ChessmanList)))==0:
                    return Chessman(MainGame.player2Color, item.x, next_y)
        for i in range(0,18):
            for j in range(0, 18):
                fi= filter(lambda x: x.x == i and x.y == j,  MainGame.ChessmanList)
                if len(list(fi)) == 0 :
                    return  Chessman(MainGame.player2Color, i, j)
        return None
    #判断游戏胜利
    def VictoryOrDefeat(self):
        for item in  MainGame.ChessmanList:
            if self.calHorizontalCount(item) == 5 or self.calVerticalityCount(item) == 5 or self.calBevelsUpCount(item) == 5 or self.calBevelsDownCount(item)==5:
                txt =""
                if item.troops == MainGame.player1Color :
                    txt = "玩家"
                else:
                    txt = "电脑"
                MainGame.window.blit(self.getTextSuface("%s获胜" % txt), (SCREEN_WIDTH-100, 200))
                MainGame.Putdownflag = MainGame.overColor
                return
    def calHorizontalCount(self,chessman):
        count = 1
        for i in range(1, 5):
            fi = filter(lambda x: x.troops == chessman.troops and x.x == chessman.x and x.y == chessman.y + i,
                        MainGame.ChessmanList)
            if len(list(fi)) == 1:
                count += 1
            else:
                break
        return count
    def calVerticalityCount(self, chessman):
        count = 1
        for i in range(1, 5):
            fi = filter(lambda x:x.troops==chessman.troops and x.x == chessman.x+ i and x.y == chessman.y  , MainGame.ChessmanList)
            if len(list(fi)) == 1:
                count += 1
            else:
                break
        return count
    def calBevelsUpCount(self, chessman):
        count = 1
        for i in range(1, 5):
            fi = filter(lambda x: x.troops == chessman.troops and x.x == chessman.x + i and x.y == chessman.y - i,
                        MainGame.ChessmanList)
            if len(list(fi)) == 1:
                count += 1
            else:
                break
        return count
    def calBevelsDownCount(self, chessman):
        count = 1
        for i in range(1, 5):
            fi = filter(lambda x: x.troops == chessman.troops and x.x == chessman.x + i and x.y == chessman.y + i,
                        MainGame.ChessmanList)
            if len(list(fi)) == 1:
                count += 1
            else:
                break
        return count
    def getTextSuface(self, text):
        pygame.font.init()
        # print(pygame.font.get_fonts())
        font = pygame.font.SysFont('kaiti', 18)
        txt = font.render(text, True, TEXT_COLOR)
        return txt
    def endGame(self):
        print("exit")
        exit()
class   Chessman():
    def __init__(self,t,x,y):
        self.images = {
            'B' : pygame.image.load("imgs/black.gif"),
            'W' : pygame.image.load('imgs/white.gif'),
            'N' : pygame.image.load("imgs/black.gif"),
        }
        self.troops = t
        self.image = self.images[self.troops]
        self.x = x
        self.y = y
        self.rect = self.image.get_rect()
        self.rect.left = MainGame.Start_X + x * MainGame.Line_Span - MainGame.Line_Span/2
        self.rect.top =  MainGame.Start_Y + y * MainGame.Line_Span - MainGame.Line_Span/2
    def displaychessman(self):
        if self.troops != 'N':
            self.image = self.images[self.troops]
            MainGame.window.blit(self.image,self.rect)
if __name__ == '__main__':
    MainGame().startGame()第二版已发布与另外一篇博文,有兴趣的可以去查看下载。
本文的文字及图片来源于网络加上自己的想法,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。
Python开发五子棋游戏【新手必学】的更多相关文章
- Python自动输入【新手必学】
		前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:哈喽哈嘿哈 这篇文章是我的第一篇文章,写的不好的地方,请大家多多指教哈 ... 
- Python整合pdf【新手必学】
		在下载课件时往往会分成很多个小的pdf,一个也就几页,想要整合成一整个大pdf,于是百度了一下,网上有很多在线的pdf整合器,但是由于这蛋疼的网速,流量还要花钱,还是想要本地搞. 说python是万能 ... 
- Python爬虫之cookie的获取、保存和使用【新手必学】
		前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:huhanghao Cookie,指某些网站为了辨别用户身份.进行ses ... 
- Python学习笔记—自动化部署【新手必学】
		前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:唯恋殊雨 目录 pexpect fabric pexpect P ... 
- Python基础语法总结【新手必学】
		前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:weixin_45189038直接上知识点: 1. 注释 单行注释: ... 
- Python 如何定义只读属性?【新手必学】
		前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:Daniel2333如果还没学到属性问题,看不懂不怪你,可以先去小编的P ... 
- 【新手必学】Python爬虫之多线程实战
		前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:清风化煞_ 正文 新手注意:如果你学习遇到问题找不到人解答,可以点 ... 
- Python自定义包引入【新手必学】
		前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:sys_song python中的Module是比较重要的概念.常见的情 ... 
- Python + Selenium +Chrome 批量下载网页代码修改【新手必学】
		Python + Selenium +Chrome 批量下载网页代码修改主要修改以下代码可以调用 本地的 user-agent.txt 和 cookie.txt来达到在登陆状态下 批量打开并下载网页, ... 
随机推荐
- iloc与loc的区别
			pandas.DataFrame.iloc iloc基于位置进行索引,主要是整数位置,也可以用布尔数组 iloc的输入可以是:单个整数.整数列表或数组.整数切片.布尔数组 pandas.DataFr ... 
- NVMe概况
			简介 NVMe是为满足企业和客户系统需求,利用基于PCIe的固态存储,而精心设计的一个优化的,高效的,可伸缩主机控制器接口.NVMe是为非易失性内存(NVM)技术从头开始全新构建的,目的在于超越硬盘驱 ... 
- 【转】常见的hash算法及其原理
			Hash,一般翻译做“散列”,也有直接音译为“哈希”的,就是把任意长度的输入(又叫做预映射, pre-image),通过散列算法,变换成固定长度的输出,该输出就是散列值.这种转换是一种压缩映射,也就是 ... 
- hashmap与currentHashMap
			hashmap的缺点 多线程不安全,在并发场景下使用时容易出现死循环,脏读问题等 死循环:https://juejin.im/post/5a66a08d5188253dc3321da0 (这篇好点)h ... 
- Gin_入门
			1. 创建路由 1.1 Restful风格的API gin支持Restful风格的API 即Representational State Transfer的缩写.直接翻译的意思是"表现层状态 ... 
- echats--visualmap
			visualmap 既图片左下角的筛选按钮 1.对颜色的区分 visualMap: [ { top: 20, left: 0, right: null, // 设置文本为红色 textStyle: { ... 
- 设置canvas的背景成白色
			解决方案一:将透明的pixel设成白色 因为png图片的背景都是透明的,所以我们可以寻找透明的pixel,然后将其全部设置成白色,核心代码如下: JavaScript Code复制内容到剪贴板 // ... 
- python skimage库的安装
			skimage库需要依赖 numpy+mkl 和scipy 1.打开运行,输入cmd回车,输入python回车,查看python版本 
- 通过maven 打docker 镜像包,出错ADD failed: stat /var/lib/docker/tmp/docker-builderXXXXXX: no such file or dir
			出现问题的原因很简单,没有maven打包生成jar包. 
- java  is 和 == ,以及equal
			package string; public class MemAddrChange { public static void main(String[] args) { // const 常量区, 
