يوجد لدي لعبة XO ال xمدخلة من المستخدم وال o مدخلة من كود البايثون كيف يمكن التعامل مع هذا الملف ل عرض النتائج على المتصفح علما ان تم استخدام laravel ك ايطار عمل كود اللعبة مكتوب بلغة جافا سكريبت في حال وجود طريقة مبسطة بشكل اخر اتمنى ان يتم طرحه عليي وشكرا
var currentPlayer = "X";
var moves = [null, null, null, null, null, null, null, null, null];
var winningCombos = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
function makeMove(cell) {
if (moves[cell] === null) {
moves[cell] = currentPlayer;
document.getElementsByClassName("cell")[cell].innerText = currentPlayer;
if (checkWin(currentPlayer)) {
alert(currentPlayer + " wins!");
resetBoard();
} else if (moves.every((move) => move !== null)) {
alert("It's a tie!");
resetBoard();
} else {
currentPlayer = currentPlayer === "X" ? "O" : "X";
}
}
}
function checkWin(player) {
return winningCombos.some((combo) => {
return combo.every((cell) => moves[cell] === player);
});
}
function resetBoard() {
moves = [null, null, null, null, null, null, null, null, null];
var cells = document.getElementsByClassName("cell");
for (var i = 0; i < cells.length; i++) {
cells[i].innerText = "";
}
}
# %% [markdown]
# ## XO
# %% [markdown]
# ### Game Constants :
# %%
from collections import Counter
BOARD_EMPTY = 0
BOARD_PLAYER_X = 1
BOARD_PLAYER_O = -1
# %% [markdown]
# ### The print_board function :
# %% [markdown]
# that would take in the state and print the current state to the user.
#
# %%
def print_board(s):
def convert(num):
if num == BOARD_PLAYER_X:
return 'X'
if num == BOARD_PLAYER_O:
return 'O'
return '_'
i = 0
for _ in range(3):
for _ in range(3):
print(convert(s[i]), end=' ')
i += 1
print()
def mapToBoard(item):
if item == 'x':
return BOARD_PLAYER_X
elif item == 'o':
return BOARD_PLAYER_O
return BOARD_EMPTY
def mapToChar(item):
if item == 1:
return 'x'
elif item == -1:
return 'o'
return '-'
# %% [markdown]
# ### The player(s) function :
# %% [markdown]
# is defined to take the state of the game and return whose turn it is:
#
# Player X’s or Player O’s. We can achieve this simply by knowing the number of the Xs and Os already placed in the state.
#
# If there are more Xs than Os, then it is O’s turn, otherwise it is X’s turn. Obviously, if the sum of both Xs and Os is 9, then the game is at a terminal state.
# %%
def player(s):
counter = Counter(s)
x_places = counter[1]
o_places = counter[-1]
if x_places + o_places == 9:
return None
elif x_places > o_places:
return BOARD_PLAYER_O
else:
return BOARD_PLAYER_X
# %% [markdown]
# ### The Actions Function :
# %% [markdown]
# The actions(s) function takes in a state and returns the list of available moves. This list contains all moves, whether desirable or undesirable.
#
# We go through the state and look for the empty cells.
# We return a list a tuple where each tuple (p, i) where p is the player and i is the index of this next move.
# %%
def actions(s):
play = player(s)
actions_list = [(play, i) for i in range(len(s)) if s[i] == BOARD_EMPTY]
return actions_list
# %% [markdown]
# ### The Result Function
# %% [markdown]
# This is a fairly simple function.
# This function takes in two parameters:
#
# 1- s — the state of the board.
# 2- a — the tuple of the player and the index they want to play.
# The function returns a new state, where the action is applied to the state provided in the parameters.
#
# Note that I am returning a copy of the state so that this does not affect the actual state coming through the parameters.
# %%
def result(s, a):
(play, index) = a
s_copy = s.copy()
s_copy[index] = play
return s_copy
# %% [markdown]
# ### The Terminal Function
# %% [markdown]
# We have spoken about terminal state before. This function will take in the state of the game and return a nullable number value.
#
# 1- If the game is not over, the function will return None.
#
# 2- If the game is a tie, the function will return 0.
#
# 3- If Player X wins the game, the function will return BOARD_PLAYER_X.
#
# 4- If Player O wins the game, the function will return BOARD_PLAYER_O.
#
# This is going to be a lot of if checks to verify if any of the player has won. I presume you know how to play Tic Tac Toe to know the rules of the game , If you are unsure about how the checks are working, I suggest working out the cell numbers with their respective index to compute the algorithm.
# %%
def terminal(s):
for i in range(3):
# Checking if a row is filled and equal.
if s[3 * i] == s[3 * i + 1] == s[3 * i + 2] != BOARD_EMPTY:
return s[3 * i]
# Checking if a column is filled and equal.
if s[i] == s[i + 3] == s[i + 6] != BOARD_EMPTY:
return s[i]
# Checking if a diagonal is filled and equal.
if s[0] == s[4] == s[8] != BOARD_EMPTY:
return s[0]
if s[2] == s[4] == s[6] != BOARD_EMPTY:
return s[2]
# Checking if the game has no more moves available
if player(s) is None:
return 0
# Return None if none of the previous conditions satisfy.
return None
# %% [markdown]
# ### The Utility Function :
# %% [markdown]
# This is the most important function in the entire board. The utility function will take in the current state as a parameter, and it will return the score of that particular state.
#
# As described in the Minimax algorithm above, we will consider all the actions in a particular state recurse with the result of the applied action. This will continue until we reach the terminal state, where we return the score.
#
# 1- If the game results in a tie, we return 0.
#
# 2- If the game results in X winning, we return 1 (Max player)
#
# 3- If the game results in O winning, we return -1 (Min player).
#
# Player X is trying to maximize his score. It will look through the list of its children and return the action with the maximum score.
#
# Player O is, likewise, trying to minimize his score. It will return the action associated with the minimum score.
#
# However, there is a small problem with this, function. If there are two different paths that lead to winning the game, there is no way to differentiate between the two paths. Hence, we need to define another parameter called cost. This parameter will tell you how deep the algorithm had to go till it reached the terminal state.
#
# Now, when we actually implement the minimax algorithm, we will sort the desired output with the cost.
# %%
def utility(s, cost):
term = terminal(s)
if term is not None:
# Return the cost of reaching the terminal state
return (term, cost)
action_list = actions(s)
utils = []
for action in action_list:
new_s = result(s, action)
# Every recursion will be an increment in the cost (depth)
utils.append(utility(new_s, cost + 1))
# Remember the associated cost with the score of the state.
score = utils[0][0]
idx_cost = utils[0][1]
play = player(s)
if play == BOARD_PLAYER_X:
for i in range(len(utils)):
if utils[i][0] > score:
score = utils[i][0]
idx_cost = utils[i][1]
else:
for i in range(len(utils)):
if utils[i][0] < score:
score = utils[i][0]
idx_cost = utils[i][1]
# Return the score with the associated cost.
return (score, idx_cost)
# %% [markdown]
# ### The Minimax Function :
# %% [markdown]
# The minimax(s) function can be considered to be an extension of the utility function that returns the desired action to take for a given state s.
# %%
def minimax(s):
action_list = actions(s)
utils = []
for action in action_list:
new_s = result(s, action)
utils.append((action, utility(new_s, 1)))
# Each item in utils contains the action associated
# the score and "cost" of that action.
# if utils has no objects, then return a default action and utility
if len(utils) == 0:
return ((0, 0), (0, 0))
# Sort the list in ascending order of cost.
sorted_list = sorted(utils, key=lambda l : l[0][1])
# Since the computer shall be Player O,
# It is safe to return the object with minimum score.
action = min(sorted_list, key = lambda l : l[1])
return action
# %% [markdown]
# ### the playTicTacToe function :
# %%
def playTicTacToe(input_param , input_x ,input_y):
s = list(map(mapToBoard, [char for char in input_param]))
x = int(input_x)
y = int(input_y)
if terminal(s) is None:
play = player(s)
# Take input from user
index = 3 * x + y
if s[index] == BOARD_EMPTY:
# Apply the action and print the board
s = result(s, (BOARD_PLAYER_X, index))
#The is computer is playing its turn by running the minimax algorithm
action = minimax(s)
# Apply the returned action to the state and print the board
s = result(s, action[0])
return s
# %% [markdown]
# ### Main XO :
# %%
# Initializing the state
s = [BOARD_EMPTY for _ in range(9)]
s
# %%
input_param = "-x-o-----"
input_x = "1"
input_y = "1"
# %%
def playXO(input_param , input_x , input_y):
output_arr = playTicTacToe(input_param , input_x , input_y)
output_str = ''.join(list(map(mapToChar, [char for char in output_arr])))
return output_str
# %% [markdown]
# ## Tiles
# %%
import random
# %%
def getRandomList():
ls = list(range(0 , 9))
random.shuffle(ls)
return ls
# %%
randomlist = getRandomList()
print(randomlist)
# %%
def playTile(inputList):
inputls = list(map(int, inputList))
return randomlist == inputls
# %%
solution = "0123455678"
playTile(solution)