import sys
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QProgressBar, QPushButton
from PyQt5.QtCore import Qt, QRect, QTimer
import random
# Tic Tac Toe class
class TicTacToe:
def __init__(self):
self.board = np.zeros((3, 3), dtype=int)
self.player = 1
self.gameOver = False
def play_move(self, x, y):
if not self.gameOver and self.board[x][y] == 0:
self.board[x][y] = self.player
if self.check_win(x, y):
self.gameOver = True
else:
self.player = -self.player
return True
return False
def check_win(self, x, y):
if np.abs(np.sum(self.board[x])) == 3 or np.abs(np.sum(self.board[:, y])) == 3:
return True
if x == y and np.abs(np.sum(np.diag(self.board))) == 3:
return True
if x + y == 2 and np.abs(np.sum(np.diag(np.fliplr(self.board)))) == 3:
return True
return False
def reset(self):
self.board = np.zeros((3, 3), dtype=int)
self.player = 1
self.gameOver = False
# GUI class
class TicTacToeGUI(QMainWindow):
def __init__(self, parent=None):
super(TicTacToeGUI, self).__init__(parent)
self.setWindowTitle('Tic Tac Toe')
self.setFixedSize(300, 400)
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
grid_layout = QGridLayout()
central_widget.setLayout(grid_layout)
self.buttons = []
for x in range(3):
for y in range(3):
btn = QPushButton("", self)
btn.setGeometry(QRect(100 * x, 100 * y, 100, 100))
btn.clicked.connect(lambda state, x=x, y=y: self.play_move(x, y))
grid_layout.addWidget(btn, x, y)
self.buttons.append(btn)
self.progress_bar = QProgressBar(self)
self.progress_bar.setGeometry(QRect(0, 300, 300, 25))
self.status_label = QLabel(self)
self.status_label.setGeometry(QRect(0, 325, 300, 25))
self.status_label.setAlignment(Qt.AlignCenter)
def play_move(self, x, y):
if game.play_move(x, y):
self.update_board()
if not game.gameOver:
QTimer.singleShot(1, self.ai_move)
def ai_move(self):
self.learn_ai_data()
game.play_move(*make_best_move())
self.update_board()
def update_board(self):
for x in range(3):
for y in range(3):
index = x * 3 + y
btn = self.buttons[index]
if game.board[x][y] == 1:
btn.setText('X')
elif game.board[x][y] == -1:
btn.setText('O')
else:
btn.setText('')
def reset_board(self):
game.reset()
self.update_board()
def ai_data_to_train_data(self):
X = []
Y = []
for state, action, next_state, reward in ai_data:
current_q = model.predict(state.reshape(-1, 9))
target_q = np.copy(current_q)
target_q[0, action] = reward + np.max(model.predict(next_state.reshape(-1, 9)))
X.append(state)
Y.append(target_q)
X = np.array(X)
Y = np.array(Y)
return X, Y
def learn_ai_data(self):
self.status_label.setText("AI learning...")
X, Y = self.ai_data_to_train_data()
model.train_on_batch(X, Y)
def make_best_move(self):
scores = np.zeros((3, 3))
for x in range(3):
for y in range(3):
if game.board[x][y] == 0:
new_board = np.copy(game.board)
new_board[x][y] = game.player
reward = model.predict(new_board.reshape(-1, 9))
scores[x][y] = reward[0]
else:
scores[x][y] = -np.inf
best_move = np.unravel_index(np.argmax(scores), (3, 3))
return best_move
# Tic Tac Toe initialization
game = TicTacToe()
# Model definition
model = Sequential([
Dense(32, activation="relu", input_shape=(9,)),
Dense(32, activation="relu"),
Dense(9, activation="linear")
])
model.compile(optimizer=Adam(lr=0.01), loss="mse")
# Data gathering
ai_data = []
# Main function
if __name__ == "__main__":
app = QApplication(sys.argv)
tic_tac_toe_gui = TicTacToeGUI()
tic_tac_toe_gui.show()
sys.exit(app.exec_())