search
HomeBackend DevelopmentPython TutorialHow to implement three-piece chess game in python

1. Basic process

The implementation logic of the three-piece chess game is as follows:

1. Create an initialized 3*3 chessboard;
2. The player holds the U piece and moves the piece first;
3. Determination of victory or defeat [win, loss, draw], if the outcome is not decided, continue as follows
4. The computer holds the T piece and makes a move;
5. Determination of victory or defeat, if the victory is If the result is negative, continue from step 2

2. Basic steps

Select 1 to start the game, and select 2 to exit the game

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. Initialize the chessboard and print the chessboard

The three-piece chess board is a 3*3 square matrix and is stored in a list in python.

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

So how to print out this storage list and turn it into a chessboard?

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

How to implement three-piece chess game in python

3. Player’s move

The player selects the horizontal and vertical coordinates of the move on the 3*3 chessboard. The coordinate point needs to meet the following requirements: 1. The point is within the chessboard; 2. The point has not yet been placed.

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. Computer placement

Computer placement algorithm:

4.1. First check the chessboard to see if there are two consecutive pieces on the chessboard occupied by the computer. The state of chess. If it already exists, get the coordinate point that can promote victory and make a move T;

4.2. If 4.1 is not satisfied, check the chessboard again to see if there are already two pieces in a row on the board that the player has occupied. The state of becoming or about to become a chess piece. If it already exists, get the coordinate point where the player is about to win, and move the T to intercept;

4.3. If 4.1 and 4.2 are not satisfied, select a favorable point on the computer side to make the move;

A. First determine whether the central position [1][1] is occupied. If not, this is the most advantageous point. When the [1][1] point is occupied, the player's four horizontal, vertical, diagonal, and sub-diagonal lines are blocked;
B, the secondary advantageous points are the four on the 3*3 chessboard Corner, each corner occupied will block the player's three routes;
C. The last advantageous point is the center of each side, which will block the player's two routes;

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. Win or Lose Determination

Final result: Lose, win, draw D
Determination process: Determine whether player U or computer T connects three pieces on each horizontal line, vertical line, and diagonal line , if so, that side wins; when the entire chess surface is occupied but neither the player nor the computer succeeds, it means a draw.

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;

3. Overall code

# 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. Result display

4.1 The following screenshot shows the process of computer interception, occupying a favorable position, and taking the lead in making a move

How to implement three-piece chess game in python

How to implement three-piece chess game in python

How to implement three-piece chess game in python

The above is the detailed content of How to implement three-piece chess game in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.