搜索
首页后端开发Python教程python怎么实现三子棋游戏

一、基本流程

三子棋游戏实现逻辑如下:

1、创建初始化3*3棋盘;
2、玩家执U子,先进行落子;
3、胜负判定【胜、负、和棋】,若胜负未分,则继续如下
4、电脑执T子,进行落子;
5、胜负判定,若胜负未分,则从步骤2继续执行

二、基本步骤

1、菜单界面

选择1是开始游戏,选择2是退出游戏

def menu():
    print('-'*20)
    print('1---------------begin')
    print('2---------------exit')
    print('please select begin or exit')
    print('-' * 20)
    while(1):
        select = input('please input:')
        if select == '1':
            begin_games()
            pass
        elif select == '2':
            print('exit the game')
            break
            #pass
    pass

2、初始化棋盘、打印棋盘

三子棋棋盘是3*3的方阵,在python中用列表来进行存储。

chess_board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

那么如何将这个存储列表打印出来,成为棋盘呢?

def init_cheaa_board(chess_board): #先对列表进行初始化
    for i in range(MAX_ROW):
        for j in range(MAX_COL):
            chess_board[i][j] = ' '
    pass

def print_chess_board(chess_board): #棋盘打印
    print('*'+'-'*7+'*'+'-'*7+'*'+'-'*7+'*')
    for i in range(MAX_ROW):
        print('|'+' '*3+chess_board[i][0]+' '*3+'|'+' '*3+chess_board[i][1]+' '*3+'|'+' '*3+chess_board[i][2]+' '*3+'|')
        print('*' + '-' * 7 + '*' + '-' * 7 + '*' + '-' * 7 + '*')
        pass
    pass

python怎么实现三子棋游戏

3、玩家落子

玩家在3*3的棋盘中选择落子的横纵坐标。坐标点需要满足:1、该点在棋盘内;2、该点还未置子。

def player_first(chess_board):
    while(1):
        x = int(input('please input x:'))
        y = int(input('please input y:'))
        if(chess_board[x][y] != ' '): #若已被置子,则重新选择坐标
            print('This position is already occupied!')
            pass
        elif(x >= MAX_ROW or y >= MAX_COL or x < 0 or y < 0): #所选坐标超出棋盘范围,重新选择坐标
            print(&#39;This position is beyond the chessboard!&#39;)
            pass
        else: #若坐标可以落子,则将该坐标置为玩家的棋子U
            chess_board[x][y] = &#39;U&#39;
            print_chess_board(chess_board)
            #return x,y
            break
            pass
    pass

4、电脑落子

电脑落子算法:

4.1、先检查一下棋盘,看电脑已占有棋面中是否已经有两子连成、即将成棋的状态。若已有,则获取可以促成胜利的坐标点,进行落子T;

4.2、若4.1不满足,则再去检查一下棋盘,看玩家已占有棋面中是否已经有两子连成、即将成棋的状态。若已有,则获取玩家即将胜利的坐标点,落子T进行拦截;

4.3、若4.1、4.2均不满足,则在棋面中选择电脑端有利的点进行落子;

A、先判断中心位置[1][1]处是否被占领,若未被占领,则这是最有利点。当占领[1][1]点时,则阻断了玩家的横、纵、正对角线、副对角线四条线路;
B、次有利点则是3*3棋盘的四个角,每占领一个角,则会阻断玩家的三条线路;
C、最后有利的点则是每条边的中心位置,会阻断玩家的两条线路;

def Intercept_player(chess_board,key):
    count2 = 0
    index2 = []
    intercept_index = {&#39;x&#39;:-1,&#39;y&#39;:-1}
    for i in range(MAX_ROW):
        index = []
        count = 0
        count1 = 0
        index1 = []
        allindex = [0,1,2]
        for j in range(MAX_ROW):
            if(chess_board[i][j] == key): #每一行的玩家落子情况
                count += 1
                index.append(j)
            if(chess_board[j][i] == key): #每一列的玩家落子情况
                #print(&#39;j&#39;+str(j)+&#39;,i&#39;+str(i)+&#39;=&#39;+chess_board[j][i])
                count1 += 1
                index1.append(j)
            if (i == j and chess_board[j][i] == key):  # 在主对角线中的玩家落子情况
                count2 += 1
                index2.append(j)
        if(count == 2):    #在每一行中  获取具体的可以拦截的位置坐标  需要排除掉已经填充的位置
            result = list(set(allindex).difference(set(index)))
            result = result[0]
            if(chess_board[i][result] == &#39; &#39;): #当这个位置可以进行拦截时,进行坐标返回
                #return i,result
                intercept_index[&#39;x&#39;] = i
                intercept_index[&#39;y&#39;] = result
                return intercept_index
        #print(count1,&#39;------->&#39;,index1)
        if (count1 == 2):  # 在每一列中 获取具体的可以拦截的位置坐标  需要排除掉已经填充的位置
            result = list(set(allindex).difference(set(index1)))
            result = result[0]
            #print(&#39;count1==2,result:&#39;,result)
            if (chess_board[result][i] == &#39; &#39;):  # 当这个位置可以进行拦截时,进行坐标返回
                intercept_index[&#39;x&#39;] = result
                intercept_index[&#39;y&#39;] = i
                return intercept_index
                #return i, result
        if (count2 == 2):  # 在主对角线上 获取具体的可以拦截的位置坐标  需要排除掉已经填充的位置
            result = list(set(allindex).difference(set(index2)))
            result = result[0]
            if (chess_board[i][result] == &#39; &#39;):  # 当这个位置可以进行拦截时,进行坐标返回
                intercept_index[&#39;x&#39;] = i
                intercept_index[&#39;y&#39;] = result
                return intercept_index
                #return i, result
    count3 = 0
    if(chess_board[0][2] == key):
        count3 += 1
    if (chess_board[1][1] == key):
        count3 += 1
    if (chess_board[2][0] == key):
        count3 += 1
    if(count3 == 2):
        if(chess_board[0][2] == &#39; &#39;):
            intercept_index[&#39;x&#39;] = 0
            intercept_index[&#39;y&#39;] = 2

        elif (chess_board[1][1] == &#39; &#39;):
            intercept_index[&#39;x&#39;] = 1
            intercept_index[&#39;y&#39;] = 1

        elif (chess_board[2][0] == &#39; &#39;):
            intercept_index[&#39;x&#39;] = 2
            intercept_index[&#39;y&#39;] = 0
    return intercept_index
    
def computer_second(chess_board):  #电脑智能出棋
    #1、先检查一下电脑是否两子成棋  若已有,则获取空位置坐标 自己先成棋
    intercept_index = Intercept_player(chess_board, &#39;T&#39;)
    if (intercept_index[&#39;x&#39;] == -1 and intercept_index[&#39;y&#39;] == -1):
        pass
    else:  # 电脑可落子
        x = intercept_index[&#39;x&#39;]
        y = intercept_index[&#39;y&#39;]
        chess_board[x][y] = &#39;T&#39;
        return
    #2、若玩家快成棋   则先进行拦截
    intercept_index = Intercept_player(chess_board,&#39;U&#39;)   #若玩家已经两子成棋  则获取空位置的坐标
    #print(&#39;intercept_index---:&#39;)
    #print(intercept_index)
    if(intercept_index[&#39;x&#39;] == -1 and intercept_index[&#39;y&#39;] == -1):
        pass
    else:  #电脑可落子
        x = intercept_index[&#39;x&#39;]
        y = intercept_index[&#39;y&#39;]
        chess_board[x][y] = &#39;T&#39;
        return
    #3、如果没有,则电脑端排棋  以促进成棋
    #3.1、 占领中心位置  如若中心位置[1,1]未被占领
    if(chess_board[1][1] == &#39; &#39;):
        chess_board[1][1] = &#39;T&#39;
        return
    #3.2、 占领四角位置  若[0,0]  [0,2]  [2,0]  [2,2]未被占领
    if (chess_board[0][0] == &#39; &#39;):
        chess_board[0][0] = &#39;T&#39;
        return
    if (chess_board[0][2] == &#39; &#39;):
        chess_board[0][2] = &#39;T&#39;
        return
    if (chess_board[2][0] == &#39; &#39;):
        chess_board[2][0] = &#39;T&#39;
        return
    if (chess_board[2][2] == &#39; &#39;):
        chess_board[2][2] = &#39;T&#39;
        return
    # 3.3、 占领每一边中心位置  若[0,1]  [1,0]  [1,2]  [2,1]未被占领
    if (chess_board[0][1] == &#39; &#39;):
        chess_board[0][1] = &#39;T&#39;
        return
    if (chess_board[1][0] == &#39; &#39;):
        chess_board[1][0] = &#39;T&#39;
        return
    if (chess_board[1][2] == &#39; &#39;):
        chess_board[1][2] = &#39;T&#39;
        return
    if (chess_board[2][1] == &#39; &#39;):
        chess_board[2][1] = &#39;T&#39;
        return

5、输赢判定

最终的结果:输、赢、和棋D
判定流程:判断每个横线、纵线、对角线上是否有玩家U或电脑T连成三子的,若有则是该方胜出;当整个棋面都被占满,但玩家和电脑都未成棋时,则说明和棋。

def chess_board_isfull(chess_board):   #判断棋盘是否填充满
    for i in range(MAX_ROW):
        if (&#39; &#39; in chess_board[i]):
            return 0
    return 1
    pass
    
def Win_or_lose(chess_board):
    isfull = chess_board_isfull(chess_board)
    for i in range(MAX_ROW):  #每一列的判断
        if( chess_board[0][i] == chess_board[1][i] == chess_board[2][i]):
            return chess_board[0][i]
            pass
        pass

    for i in range(MAX_ROW):  # 每一行的判断
        if( chess_board[i][0] == chess_board[i][1] == chess_board[i][2]):
            return chess_board[i][0]
            pass
        pass

    if (chess_board[0][0] == chess_board[1][1] == chess_board[2][2]):  # 判断棋盘正对角线
        return chess_board[0][0]

    if (chess_board[0][2] == chess_board[1][1] == chess_board[2][0]):  # 判断棋盘反对角线
        return chess_board[0][2]

    if isfull:
        return &#39;D&#39;  # 经过以上的判断,都不满足(既没赢也没输),但是棋盘也已经填充满,则说明和棋
    else:
        return &#39; &#39;

三、整体代码

# coding=utf-8import random
MAX_ROW = 3
MAX_COL = 3
#array = ['0','0','0']
chess_board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] #[array] * 3

def init_cheaa_board(chess_board):
    for i in range(MAX_ROW):
        for j in range(MAX_COL):
            chess_board[i][j] = ' '
    pass

def print_chess_board(chess_board):
    print('*'+'-'*7+'*'+'-'*7+'*'+'-'*7+'*')
    for i in range(MAX_ROW):
        print('|'+' '*3+chess_board[i][0]+' '*3+'|'+' '*3+chess_board[i][1]+' '*3+'|'+' '*3+chess_board[i][2]+' '*3+'|')
        print('*' + '-' * 7 + '*' + '-' * 7 + '*' + '-' * 7 + '*')
        pass
    pass


def player_first(chess_board):
    while(1):
        x = int(input('please input x:'))
        y = int(input('please input y:'))
        if(chess_board[x][y] != ' '):
            print('This position is already occupied!')
            pass
        elif(x >= MAX_ROW or y >= MAX_COL or x < 0 or y < 0):
            print('This position is beyond the chessboard!')
            pass
        else:
            chess_board[x][y] = 'U'
            print_chess_board(chess_board)
            #return x,y
            break
            pass
    pass

def chess_board_isfull(chess_board):   #判断棋盘是否填充满
    for i in range(MAX_ROW):
        if (' ' in chess_board[i]):
            return 0
    return 1
    pass

def Win_or_lose(chess_board):
    isfull = chess_board_isfull(chess_board)
    for i in range(MAX_ROW):  #每一列的判断
        if( chess_board[0][i] == chess_board[1][i] == chess_board[2][i]):
            return chess_board[0][i]
            pass
        pass

    for i in range(MAX_ROW):  # 每一行的判断
        if( chess_board[i][0] == chess_board[i][1] == chess_board[i][2]):
            return chess_board[i][0]
            pass
        pass

    if (chess_board[0][0] == chess_board[1][1] == chess_board[2][2]):  # 判断棋盘正对角线
        return chess_board[0][0]

    if (chess_board[0][2] == chess_board[1][1] == chess_board[2][0]):  # 判断棋盘反对角线
        return chess_board[0][2]

    if isfull:
        return 'D'  # 经过以上的判断,都不满足(既没赢也没输),但是棋盘也已经填充满,则说明和棋
    else:
        return ' '

def computer_second_random(chess_board):    #电脑随机出棋
    while(1):
        x = random.randint(0,2)
        y = random.randint(0,2)
        if(chess_board[x][y] != ' '):
            continue
        else:
            chess_board[x][y] = 'T'
            break

def Intercept_player(chess_board,key):
    count2 = 0
    index2 = []
    intercept_index = {'x':-1,'y':-1}
    for i in range(MAX_ROW):
        index = []
        count = 0
        count1 = 0
        index1 = []
        allindex = [0,1,2]
        for j in range(MAX_ROW):
            if(chess_board[i][j] == key): #每一行的玩家落子情况
                count += 1
                index.append(j)
            if(chess_board[j][i] == key): #每一列的玩家落子情况
                #print('j'+str(j)+',i'+str(i)+'='+chess_board[j][i])
                count1 += 1
                index1.append(j)
            if (i == j and chess_board[j][i] == key):  # 在主对角线中的玩家落子情况
                count2 += 1
                index2.append(j)
        if(count == 2):    #在每一行中  获取具体的可以拦截的位置坐标  需要排除掉已经填充的位置
            result = list(set(allindex).difference(set(index)))
            result = result[0]
            if(chess_board[i][result] == ' '): #当这个位置可以进行拦截时,进行坐标返回
                #return i,result
                intercept_index['x'] = i
                intercept_index['y'] = result
                return intercept_index
        #print(count1,'------->',index1)
        if (count1 == 2):  # 在每一列中 获取具体的可以拦截的位置坐标  需要排除掉已经填充的位置
            result = list(set(allindex).difference(set(index1)))
            result = result[0]
            #print('count1==2,result:',result)
            if (chess_board[result][i] == ' '):  # 当这个位置可以进行拦截时,进行坐标返回
                intercept_index['x'] = result
                intercept_index['y'] = i
                return intercept_index
                #return i, result
        if (count2 == 2):  # 在主对角线上 获取具体的可以拦截的位置坐标  需要排除掉已经填充的位置
            result = list(set(allindex).difference(set(index2)))
            result = result[0]
            if (chess_board[i][result] == ' '):  # 当这个位置可以进行拦截时,进行坐标返回
                intercept_index['x'] = i
                intercept_index['y'] = result
                return intercept_index
                #return i, result
    count3 = 0
    if(chess_board[0][2] == key):
        count3 += 1
    if (chess_board[1][1] == key):
        count3 += 1
    if (chess_board[2][0] == key):
        count3 += 1
    if(count3 == 2):
        if(chess_board[0][2] == ' '):
            intercept_index['x'] = 0
            intercept_index['y'] = 2

        elif (chess_board[1][1] == ' '):
            intercept_index['x'] = 1
            intercept_index['y'] = 1

        elif (chess_board[2][0] == ' '):
            intercept_index['x'] = 2
            intercept_index['y'] = 0
    return intercept_index


def computer_second(chess_board):  #电脑智能出棋
    #1、先检查一下电脑是否两子成棋  若已有,则获取空位置坐标 自己先成棋
    intercept_index = Intercept_player(chess_board, 'T')
    if (intercept_index['x'] == -1 and intercept_index['y'] == -1):
        pass
    else:  # 电脑可落子
        x = intercept_index['x']
        y = intercept_index['y']
        chess_board[x][y] = 'T'
        return
    #2、若玩家快成棋   则先进行拦截
    intercept_index = Intercept_player(chess_board,'U')   #若玩家已经两子成棋  则获取空位置的坐标
    #print('intercept_index---:')
    #print(intercept_index)
    if(intercept_index['x'] == -1 and intercept_index['y'] == -1):
        pass
    else:  #电脑可落子
        x = intercept_index['x']
        y = intercept_index['y']
        chess_board[x][y] = 'T'
        return
    #3、如果没有,则电脑端排棋  以促进成棋
    #3.1、 占领中心位置  如若中心位置[1,1]未被占领
    if(chess_board[1][1] == ' '):
        chess_board[1][1] = 'T'
        return
    #3.2、 占领四角位置  若[0,0]  [0,2]  [2,0]  [2,2]未被占领
    if (chess_board[0][0] == ' '):
        chess_board[0][0] = 'T'
        return
    if (chess_board[0][2] == ' '):
        chess_board[0][2] = 'T'
        return
    if (chess_board[2][0] == ' '):
        chess_board[2][0] = 'T'
        return
    if (chess_board[2][2] == ' '):
        chess_board[2][2] = 'T'
        return
    # 3.3、 占领每一边中心位置  若[0,1]  [1,0]  [1,2]  [2,1]未被占领
    if (chess_board[0][1] == ' '):
        chess_board[0][1] = 'T'
        return
    if (chess_board[1][0] == ' '):
        chess_board[1][0] = 'T'
        return
    if (chess_board[1][2] == ' '):
        chess_board[1][2] = 'T'
        return
    if (chess_board[2][1] == ' '):
        chess_board[2][1] = 'T'
        return

def begin_games():
    global chess_board
    init_cheaa_board(chess_board)
    result = ' '
    while(1):
        print_chess_board(chess_board)
        player_first(chess_board)
        result = Win_or_lose(chess_board)
        if(result != ' '):
            break
        else: #棋盘还没满,该电脑出棋
            #computer_second_random(chess_board)
            computer_second(chess_board)
            result = Win_or_lose(chess_board)
            if (result != ' '):
                break
    print_chess_board(chess_board)
    if (result == 'U'):
        print('Congratulations on your victory!')
    elif (result == 'T'):
        print('Unfortunately, you failed to beat the computer.')
    elif (result == 'D'):
        print('The two sides broke even.')


def menu():
    print(&#39;-&#39;*20)
    print(&#39;1---------------begin&#39;)
    print(&#39;2---------------exit&#39;)
    print(&#39;please select begin or exit&#39;)
    print(&#39;-&#39; * 20)
    while(1):
        select = input(&#39;please input:&#39;)
        if select == &#39;1&#39;:
            begin_games()
            pass
        elif select == &#39;2&#39;:
            print(&#39;exit the game&#39;)
            break
            #pass
    pass


if __name__ == "__main__":

    menu()
    pass

四、结果展示

4.1 在以下截图中,展示了电脑拦截、占据有利位置、并率先成棋的过程

python怎么实现三子棋游戏

python怎么实现三子棋游戏

python怎么实现三子棋游戏

以上是python怎么实现三子棋游戏的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
Python vs.C:申请和用例Python vs.C:申请和用例Apr 12, 2025 am 12:01 AM

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。 Python以简洁和强大的生态系统着称,C 则以高性能和底层控制能力闻名。

2小时的Python计划:一种现实的方法2小时的Python计划:一种现实的方法Apr 11, 2025 am 12:04 AM

2小时内可以学会Python的基本编程概念和技能。1.学习变量和数据类型,2.掌握控制流(条件语句和循环),3.理解函数的定义和使用,4.通过简单示例和代码片段快速上手Python编程。

Python:探索其主要应用程序Python:探索其主要应用程序Apr 10, 2025 am 09:41 AM

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

您可以在2小时内学到多少python?您可以在2小时内学到多少python?Apr 09, 2025 pm 04:33 PM

两小时内可以学到Python的基础知识。1.学习变量和数据类型,2.掌握控制结构如if语句和循环,3.了解函数的定义和使用。这些将帮助你开始编写简单的Python程序。

如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础?如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础?Apr 02, 2025 am 07:18 AM

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到?如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到?Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

Python 3.6加载Pickle文件报错"__builtin__"模块未找到怎么办?Python 3.6加载Pickle文件报错"__builtin__"模块未找到怎么办?Apr 02, 2025 am 07:12 AM

Python3.6环境下加载Pickle文件报错:ModuleNotFoundError:Nomodulenamed...

如何提高jieba分词在景区评论分析中的准确性?如何提高jieba分词在景区评论分析中的准确性?Apr 02, 2025 am 07:09 AM

如何解决jieba分词在景区评论分析中的问题?当我们在进行景区评论分析时,往往会使用jieba分词工具来处理文�...

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。