>  기사  >  백엔드 개발  >  파이썬으로 3인조 게임을 구현하는 방법

파이썬으로 3인조 게임을 구현하는 방법

WBOY
WBOY앞으로
2023-05-15 08:28:131260검색

1. 기본 프로세스

3피스 체스 게임의 구현 논리는 다음과 같습니다.

1. 초기화된 3*3 체스판을 만듭니다.
2. 플레이어가 U 말을 잡고 먼저 움직입니다. . 결과 결정 [승, 패, 무승부], 결과가 결정되지 않은 경우 다음과 같이 진행합니다.
4. 컴퓨터가 T 피스를 잡고 이동합니다.
5. 결정되지 않았습니다. 2단계부터 진행하세요

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 정사각형 행렬로, 파이썬의 목록에 저장됩니다.

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

파이썬으로 3인조 게임을 구현하는 방법

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] 지점이 점유되면 플레이어의 가로, 세로, 대각선 및 하위 대각선 4개가 차단됩니다.

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. 승패 결정

최종 결과: 패, 승, 무승부

판단 과정: 플레이어 U 또는 컴퓨터 T가 각 수평선, 수직선 및 대각선에 3개의 말을 연결했는지 결정합니다. 그렇다면 전체 체스가 점유되었지만 플레이어나 컴퓨터 모두 성공하지 못한 경우 해당 쪽이 승리합니다. 무승부를 의미합니다.

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. 전체 코드

# 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. 결과 표시

4.1 다음 스크린샷에서는 컴퓨터가 가로채고, 유리한 위치를 차지하고, 주도적으로 이동하는 과정을 보여줍니다

파이썬으로 3인조 게임을 구현하는 방법

파이썬으로 3인조 게임을 구현하는 방법

위 내용은 파이썬으로 3인조 게임을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제