은 디시에서 쓰지 않은글 모바일로 퍼오다보니
대부분 깨짐. 근데 어차피 코드가 중요한건 아니지.

https://chat.openai.com/chat

거짓말 안하고 코드의 대부분은 인공지능이 작성한 것입니다.

사실 틱텍토 따위야 텐서플로우를 쓰는 것보다도 직접 조지는 편이 더 좋긴 합니다만

어쩃든 틱텍토가 된다면 다른 것들도 되기는 할겁니다.

https://github.com/OhSeungho/Tic-Tac-Toe





GitHub - OhSeungho/Tic-Tac-Toe: Tic-Tac-Toe Keras, TensorFlow Programming

Tic-Tac-Toe Keras, TensorFlow Programming. Contribute to OhSeungho/Tic-Tac-Toe development by creating an account on GitHub.

github.com



데이터는 저곳 깃허브에서 퍼왔습니다.

처음에는 데이터셋을 직접 만들어볼까도 했는데

중복되지 않는 좋은 데이터셋 만드는것도 꽤나 일스럽더군요.




-1,-1,-1,-1,1,1,-1,1,1,1,0-1,-1,-1,-1,1,1,1,-1,1,1,0-1,-1,-1,-1,1,1,1,1,-1,1,0-1,-1,-1,-1,1,1,1,0,0,1,0-1,-1,-1,-1,1,1,0,1,0,1,0-1,-1,-1,-1,1,1,0,0,1,1,0The CSV file stored in this style I want to load it with Python and change it to a 2D array

우선 데이터의 형식을 제공했습니다.

이 데이터를 파이썬으로 2d array 로 인식시켜봐 하니




import pandas as pd# Load the CSV file into a pandas DataFramedf = pd.read_csv('file.csv', header=None)# Convert the DataFrame to a 2D arrayarr = df.to_numpy()print(arr)

코드를 줍니다.

해당 데이터를 그냥 사용할 수는 없습니다.

게임판 입력부분(앞의 아홉자리) 와 승패 출력부분 (뒤의 1자리) 나눠야겠죠.




I want to make a new numpy_arr with only the [0:9] part of each dimension of Arr.


import numpy as nparr = np.array([[-1,-1,-1,-1,1,1,-1,1,1,1,0],                [-1,-1,-1,-1,1,1,1,-1,1,1,0],                [-1,-1,-1,-1,1,1,1,1,-1,1,0],                [-1,-1,-1,-1,1,1,1,0,0,1,0],                [-1,-1,-1,-1,1,1,0,1,0,1,0],                [-1,-1,-1,-1,1,1,0,0,1,1,0]])numpy_arr = arr[:,0:10]

잘라줍니다. 뒤의 한 자리 자르는건 그냥 손코딩 했습니다.

근데 9자리가 아닌 10자리를 다 잘라버렸네요. 생각해보니 [0:9] 는 10개 전부 가져오는게 맞네요.

바보같은 실책입니다. 이것도 그냥 손으로 바꾸어줍니다.




Then now give me the code to learn with tensorflow.import tensorflow as tf

만들어줘.




import tensorflow as tf# Define the modelmodel = tf.keras.models.Sequential([    tf.keras.layers.Dense(10, input_shape=(10,), activation='relu'),    tf.keras.layers.Dense(1, activation='sigmoid')])# Compile the modelmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])# Train the modelmodel.fit(x_arr, y_arr, epochs=10)

텐서플로우 학습 코드를 만들어줍니다.




We're going to save this code under the name learn.py and write a new code.It's a tic-tac-to code that computers and humans alternate with.

해당 학습코드를 이용해서 틱텍토 게임 지능을 만들 생각이니 일단 게임을 만들어 봅니다.

인간과 인공지능이 번갈아 가며 두는 인공지능인데




import numpy as np# Creating the tic-tac-toe board as a 2D arrayboard = np.array([[' ', ' ', ' '],                  [' ', ' ', ' '],                  [' ', ' ', ' ']])# Function to print the boarddef print_board(board):    for i in range(3):        for j in range(3):            print(board[i][j], end=' ')        print()# Function to check if the game is a drawdef check_draw(board):    for i in range(3):        for j in range(3):            if board[i][j] == ' ':                return False    return True# Function to check if the game is wondef check_win(board, player):    # Check rows    for i in range(3):        if board[i][0] == player and board[i][1] == player and board[i][2] == player:            return True    # Check columns    for i in range(3):        if board[0][i] == player and board[1][i] == player and board[2][i] == player:            return True    # Check diagonals    if board[0][0] == player and board[1][1] == player and board[2][2] == player:        return True    if board[0][2] == player and board[1][1] == player and board[2][0] == player:        return True    return False# Game loopwhile True:    # Human's turn    print_board(board)    print("Your turn (row column): ")    row, col = map(int, input().split())    board[row][col] = 'X'    if check_win(board, 'X'):        print("You won!")        break    if check_draw(board):        print("It's a draw!")        break    # Computer's turn    print("Computer's turn: ")    row, col = np.random.randint(0, 3, size=2)    if board[row][col] == ' ':        board[row][col] = 'O'    else:        continue    if check_win(board, 'O'):        print("Computer won!")        break    if check_draw(board):        print("It's a draw!")        break

그냥 랜덤으로 두는 녀석을 만들어 줍니다.

사실 챗 지피티는 높은 확률로 깃허브를 학습한 관계로 랜덥 두기가 아닌

제대로된 인공지능을 만들 수 있을테지만 오늘 목표는 저녀석으로 텐서플로우를 뽑는 것입니다.

사실 저 코드를 그대로 쓰지는 않았습니다. 이것저것 손코딩 인공지능 양쪽으로 손대보다가




The board array in this code is inefficient.Instead, we'll use a one-dimensional numpy array of 1, 0, and -1.Only when output is converted to two dimensions,-1 will correspond to 'X', 1 to 'O', and 0 to ''.

비효율적이니 그냥 1차원 배열로 조져달라 부탁했습니다.




import numpy as npfrom learn import model# Creating the tic-tac-toe board as a 1D arrayboard = np.array([' ',' ',' ',' ',' ',' ',' ',' ',' '])# Function to print the boarddef print_board(board):    for i in range(9):        print(board[i], end=' ')        if (i+1) % 3 != 0:            print("|", end=' ')        if (i+1) % 3 == 0 and i != 8:            print()            print("------+-------+------")# Function to check if the game is a drawdef check_draw(board):    for i in range(9):        if board[i] == ' ':            return False    return True# Function to check if the game is wondef check_win(board, player):    # Check rows    for i in range(0,9,3):        if board[i] == player and board[i+1] == player and board[i+2] == player:            return True    # Check columns    for i in range(3):        if board[i] == player and board[i+3] == player and board[i+6] == player:            return True    # Check diagonals    if board[0] == player and board[4] == player and board[8] == player:        return True    if board[2] == player and board[4] == player and board[6] == player:        return True    return Falsedef board_to_array(board):    arr = np.zeros((9

해줍니다.

훨씬 났네요.

board 배열 비롯한 부분은 손으로 바꿔준뒤




I don't need board_to_array.Also, the initial value of the board is the following value.board = np.array([0,0,0,0,0,0,0,0,0])

통보합니다.




give me a check_win funtion and check_draw_funtion and print_board_funtion

고친 부분에 맞게 부분부분의 함수들도 다시 짜야 된다 말합니다.




# Function to check if the game is a drawdef check_draw(board):    for i in range(9):        if board[i] == 0:            return False    return True# Function to check if the game is wondef check_win(board, player):    # Check rows    for i in range(0,9,3):        if board[i] == player and board[i+1] == player and board[i+2] == player:            return True    # Check columns    for i in range(3):        if board[i] == player and board[i+3] == player and board[i+6] == player:            return True    # Check diagonals    if board[0] == player and board[4] == player and board[8] == player:        return True    if board[2] == player and board[4] == player and board[6] == player:        return True    return Falsedef print_board(board):    for i in range(9):        if board[i] == -1:            print("X", end=' ')        elif board[i] == 1:            print("O", end=' ')        else:            print(" ", end=' ')        if (i+1) % 3 != 0:            print("|", end=' ')        if (i+1) % 3 == 0 and i != 8:            print()            print("------+-------+------")

짜줍니다.

근데 여기서부터는 거의 다 왔는데 ... 애가...

for 문 돌려서 각 부분 예측한뒤 예측한 값중 가장 적합한 값을 쏴주는 것은

이해를 잘 못하더군요.

어쩔수 없습니다.




def computer_turn(board):    predict_arr_board = []    max_point = -1    for i in range(len(board)):        if board[i]==0:            xx = copy.deepcopy(board)            xx[i] = 1            xx = xx.reshape(1, -1)            point = model.predict(xx)[0]            if max_point<point:                select = i                max_point = point    print(select)    board[select] = 1    if check_win(board, 1):        print("You Lose!")        return True    elif check_draw(board):        print("It's a draw!")        return True    else:        return False

사실 이부분은 거의 직접 짰습니다.

조련실력의 문제인지 영어실력의 문제인진 모르겠습니다.

조금 꼬이면 아무래도 못알아 듣습니다.

머 그래도 결국....

저기까지 한거 조합하니 작동은 합니다.

다만... 인공지능이 아주 우수하진 않아서 가끔 삑사리가 납니다.

데이터셋을 더 큰걸 쓰거나 학습 에폭시를 최적으로 하거나 하면 더 나아지긴 하겠습니다만

여기서부터는 인공지능과 함꺠하는 짝코딩 이라는 주제에선 벗어나 버립니다.

결과적으로.

1. 추상적 지시가 아닌 객관적 지시를 하고

2. 특히 특정 함수를 제시한 뒤 그 함수를 개조하거나 그 함수를 사용한 다른 함수를 만들거나

하는식으로 가면 그런대로 잘 작동합니다.