IT/Python

[Python] 틱택토 게임 (Tic-Tac-Toe) + 인공지능 AI 추가

잿호 2023. 9. 18. 23:31

- 첫 실행 -

 

설계

1. 최소최대 알고리즘(Minimax algorithm) 을 활용하여 전 게시글의 "Tic-Tac-Toe"게임에 AI기능을 추가했다.

2. AI는 모든 경우에서 최선의 수를 두어 무승부 혹은 승리를 가져간다.

 


코드

import random

board = [' ' for _ in range(9)]

def show_board():
    print(f'{board[0]} | {board[1]} | {board[2]}')
    print('- | - | -')
    print(f'{board[3]} | {board[4]} | {board[5]}')
    print('- | - | -')
    print(f'{board[6]} | {board[7]} | {board[8]}')

def check_win(player):
    win_values = [
        [0, 1, 2], [3, 4, 5], [6, 7, 8], 
        [0, 3, 6], [1, 4, 7], [2, 5, 8], 
        [0, 4, 8], [2, 4, 6]  
    ]
    for value in win_values:
        if all(board[i] == player for i in value):
            return True
    return False

def minimax(board, depth, is_maximum):
    if check_win('O'):
        return 1
    if check_win('X'):
        return -1
    if ' ' not in board:
        return 0

    if is_maximum:
        best_score = -float('inf')
        for i in range(9):
            if board[i] == ' ':
                board[i] = 'O'
                score = minimax(board, depth + 1, False)
                board[i] = ' '
                best_score = max(score, best_score)
        return best_score
    else:
        best_score = float('inf')
        for i in range(9):
            if board[i] == ' ':
                board[i] = 'X'
                score = minimax(board, depth + 1, True)
                board[i] = ' '
                best_score = min(score, best_score)
        return best_score

def com_act():
    best_score = -float('inf')
    best_act = None
    for i in range(9):
        if board[i] == ' ':
            board[i] = 'O'
            score = minimax(board, 0, False)
            board[i] = ' '
            if score > best_score:
                best_score = score
                best_act = i
    return best_act

player = 'X'
while True:
    show_board()
    
    if player == 'X':
        choice = int(input('빈 칸에 0부터 8까지의 숫자를 입력하세요: '))-1
        if board[choice] == ' ':
            board[choice] = player
        else:
            print('해당 위치에는 이미 기호가 있습니다. 다른 위치를 선택하세요.')
            continue     
    else:
        choice = com_act()
        board[choice] = 'O'
    
    if check_win(player):
        show_board()
        if player == 'X':
            print('플레이어 X가 이겼습니다!')
        else:
            print('컴퓨터가 이겼습니다!')
        break
    if ' ' not in board:
        show_board()
        print('무승부입니다!')
        break
    
    player = 'O' if player == 'X' else 'X'

 

 


실행

01234
- 실행 -

 


Tic-Tac-Toe 게임

 


마무리

이전 포스팅에 AI기능을 추가 해봤습니다.  

 

2023.09.17 - [IT/Python] - [Python] 틱택토 게임 (Tic-Tac-Toe)

 

[Python] 틱택토 게임 (Tic-Tac-Toe)

Tic-Tac-Toe(틱택토) 게임? 틱택토(tic-tac-toe)는 두 명이 번갈아가며 O와 X를 3×3 판에 써서 같은 글자를 가로, 세로, 혹은 대각선 상에 놓이도록 하는 놀이이다. 오목 룰과 흡사하다. 코드 board = [' ' for

rairo.tistory.com

반응형