Python 五子棋练习

简单实现五子棋,后台窗口打印棋盘

import copy
import time
from _pydecimal import Context, ROUND_HALF_UP

"""五子棋"""
whiteDot = "白"
blackDot = "黑"
initDot = "+"


class Wuziqi:
    def __init__(self, title, w, h):
        self.__exitFlag = 0
        self.__title = title
        self.__w = w
        self.__h = h
        self.__count = 0
        self.__chessboard = []
        self.__whiteCount = 0
        self.__blackCount = 0
        self.__beginTime = time.time()
        # 初始化棋盘
        for i in range(0, self.__h + 1):
            hList = []
            for j in range(0, self.__w + 1):
                hList.append(initDot)
            self.__chessboard.append(hList)
        # 打印棋盘
        self.printChessboard()

    def startGame(self):  # 启动游戏
        print("开始{}游戏,退出程序输入:exit".format(self.__title))
        while not self.__exitFlag:
            try:
                obj = input("请下棋(x-y): ")
                if obj == "exit":
                    self.__exitFlag = 1
                    break
                x, y = map(int, obj.split("-"))
                self.playChess(x, y)
            except Exception as e:
                print("棋子越界: {}".format(e))
        print("游戏结束,退出程序")

    def exitGame(self, dot):  # 退出游戏
        self.__exitFlag = 1
        beginTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.__beginTime))
        nowTime = time.time()
        nowTimeFormat = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(nowTime))
        timeConsuming = Context(prec=3, rounding=ROUND_HALF_UP).create_decimal(nowTime - self.__beginTime)
        print("{}方胜利, 开始时间:{},结束时间:{},总耗时:{} s".format(dot, beginTime, nowTimeFormat, timeConsuming))

    def printChessboard(self):  # 打印棋盘
        print("========== 棋盘 ==========")
        count = 0
        # 棋盘水平坐标
        wList = []
        for i in range(self.__w + 1):
            if i == 0:
                wList.append("x|y")
            wList.append(str(i) + "|")
        # 深拷贝棋盘
        copyList = copy.deepcopy(self.__chessboard)
        for item in copyList:
            # 棋盘垂直坐标
            item.insert(0, str(count) + "|")
            count += 1
        count = 0
        # 打印棋盘
        for hList in copyList:
            if count == 0:
                for i in wList:
                    print(i, end="    ")
                print("\n")
            count += 1
            for j in hList:
                if j == whiteDot or j == blackDot:
                    print(j, end="    ")
                else:
                    print(j, end="     ")
            print("\n")

    def playChess(self, x, y):  # 下棋
        dot = self.__chessboard[x][y]
        if dot == whiteDot or dot == blackDot:
            print("棋子已下")
            self.printChessboard()
            return
        if self.__count % 2 == 0:  # 偶数为白
            self.__chessboard[x][y] = whiteDot
            self.__whiteCount += 1
        else:
            self.__chessboard[x][y] = blackDot
            self.__blackCount += 1
        self.__count += 1
        self.checkSuccess(x, y)
        self.printChessboard()

    def checkSuccess(self, x, y):  # 验证哪方连成五子,算法:获取落子的横/竖/斜线的五个棋子,放在数组中,验证是否存在连续五个
        dot = self.__chessboard[x][y]
        # 棋子小于5则不进行验证
        if (whiteDot == dot and self.__whiteCount < 5) or (blackDot == dot and self.__blackCount < 5):
            return
        # 横排
        chessList = self.__chessboard[x].copy()
        count = 0
        index = y
        while index >= 0:
            if chessList[index] == dot:
                count += 1
            else:
                break
            index -= 1
            if count == 5:
                break
        if count == 5:
            self.exitGame(dot)
            return
        index = y
        while index <= self.__h:
            if chessList[index] == dot:
                count += 1
            else:
                break
            index += 1
            if count == 6:
                break
        if count == 6:
            self.exitGame(dot)
        # 竖排
        count = 0
        index = x
        while index <= x:
            if dot == self.__chessboard[index][y]:
                count += 1
            else:
                break
            index -= 1
            if count == 5:
                break
        if count == 5:
            self.exitGame(dot)
            return
        index = x
        while index <= self.__w:
            if dot == self.__chessboard[index][y]:
                count += 1
            else:
                break
            index += 1
            if count == 6:
                break
        if count == 6:
            self.exitGame(dot)
        # 左下角线(0,0) - (4,4)
        count = 0
        index = x
        yIndex = y
        while index >= 0:
            if dot == self.__chessboard[index][yIndex]:
                count += 1
            else:
                break
            index -= 1
            yIndex -= 1
            if count == 5:
                break
        if count == 5:
            self.exitGame(dot)
            return
        index = x
        yIndex = y
        while index <= self.__w:
            if dot == self.__chessboard[index][yIndex]:
                count += 1
            else:
                break
            index += 1
            yIndex += 1
            if count == 6:
                break
        if count == 6:
            self.exitGame(dot)
            return
        # 右上角线(4,0) - (0,4)
        count = 0
        index = x
        yIndex = y
        while index >= 0:
            if dot == self.__chessboard[index][yIndex]:
                count += 1
            else:
                break
            index -= 1
            yIndex += 1
            if count == 5:
                break
        if count == 5:
            self.exitGame(dot)
            return
        index = x
        yIndex = y
        while index <= self.__w:
            if dot == self.__chessboard[index][yIndex]:
                count += 1
            else:
                break
            index -= 1
            yIndex += 1
            if count == 6:
                break
        if count == 6:
            self.exitGame(dot)


if __name__ == "__main__":
    game = Wuziqi("五子棋", 4, 4)
    # 横排
    # game.playChess(0, 0)
    # game.playChess(1, 0)
    # game.playChess(0, 1)
    # game.playChess(1, 1)
    # game.playChess(0, 2)
    # game.playChess(1, 2)
    # game.playChess(0, 3)
    # game.playChess(1, 3)
    # game.playChess(0, 4)
    # 竖排
    # game.playChess(0, 0)
    # game.playChess(0, 1)
    # game.playChess(1, 0)
    # game.playChess(1, 1)
    # game.playChess(2, 0)
    # game.playChess(2, 1)
    # game.playChess(3, 0)
    # game.playChess(3, 1)
    # game.playChess(4, 0)
    # 左下角(0,0) - (4-4)
    # game.playChess(0, 0)
    # game.playChess(0, 1)
    # game.playChess(1, 1)
    # game.playChess(1, 2)
    # game.playChess(2, 2)
    # game.playChess(2, 3)
    # game.playChess(3, 3)
    # game.playChess(3, 4)
    # game.playChess(4, 4)
    # 右上角线(4,0) - (0,4)
    # game.playChess(0, 4)
    # game.playChess(1, 4)
    # game.playChess(1, 3)
    # game.playChess(2, 3)
    # game.playChess(2, 2)
    # game.playChess(3, 2)
    # game.playChess(3, 1)
    # game.playChess(4, 1)
    # game.playChess(4, 0)
    game.startGame()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值