Python

(파이썬) 틱택토 Tic-Tac-Toe 게임 만들기

고니자니 2024. 3. 28. 16:16
반응형

파이썬으로 간단하게 구현한 tic-tac-toe(틱택토) 게임입니다.

한 플레이어가 이기거나 게임이 무승부로 끝날 때까지 두 플레이어가 차례로 자신의 동작을 입력할 수 있습니다.

tic-tac-toe 게임

 

def print_board(board):
    """Prints the current state of the board."""
    for row in board:
        print("|".join(row))
        print("-" * 5)

def check_winner(board):
    """Checks if there is a winner."""
    # Check rows
    for row in board:
        if row[0] == row[1] == row[2] != ' ':
            return True

    # Check columns
    for col in range(3):
        if board[0][col] == board[1][col] == board[2][col] != ' ':
            return True

    # Check diagonals
    if board[0][0] == board[1][1] == board[2][2] != ' ':
        return True
    if board[0][2] == board[1][1] == board[2][0] != ' ':
        return True

    return False

def is_board_full(board):
    """Checks if the board is full."""
    for row in board:
        if ' ' in row:
            return False
    return True

def main():
    # Initialize the board
    board = [[' ' for _ in range(3)] for _ in range(3)]

    # Player X starts the game
    current_player = 'X'

    # Game loop
    while True:
        print_board(board)

        # Get player's move
        while True:
            row = int(input("Enter row (0, 1, or 2) for your move: "))
            col = int(input("Enter column (0, 1, or 2) for your move: "))
            if 0 <= row <= 2 and 0 <= col <= 2 and board[row][col] == ' ':
                break
            else:
                print("Invalid move. Try again.")

        # Update the board
        board[row][col] = current_player

        # Check for a winner
        if check_winner(board):
            print_board(board)
            print(f"Player {current_player} wins!")
            break

        # Check for a draw
        if is_board_full(board):
            print_board(board)
            print("It's a draw!")
            break

        # Switch player
        current_player = 'O' if current_player == 'X' else 'X'

if __name__ == "__main__":
    main()

 

실행한 화면입니다.

tic-tac-toe 게임

반응형