Lab Left Ai
Lab Left Ai
Lab Journal 09
SAMMAR KHALIL
01-134191-099
Procedure/Program:
MinMax
import time
class Game:
def __init__(self):
self.initialize_game()
def initialize_game(self):
self.current_state = [['.','.','.'],
['.','.','.'],
['.','.','.']]
def is_valid(self, px, py):
if px < 0 or px > 2 or py < 0 or py > 2:
return False
elif self.current_state[px][py] != '.':
return False
else:
return True
def is_end(self):
for i in range(0, 3):
if (self.current_state[0][i] != '.' and
self.current_state[0][i] == self.current_state[1][i] and
self.current_state[1][i] == self.current_state[2][i]):
return self.current_state[0][i]
for i in range(0, 3):
if (self.current_state[i] == ['X', 'X', 'X']):
return 'X'
elif (self.current_state[i] == ['O', 'O', 'O']):
return 'O'
if (self.current_state[0][0] != '.' and
self.current_state[0][0] == self.current_state[1][1] and
self.current_state[0][0] == self.current_state[2][2]):
return self.current_state[0][0]
if (self.current_state[0][2] != '.' and
self.current_state[0][2] == self.current_state[1][1] and
self.current_state[0][2] == self.current_state[2][0]):
return self.current_state[0][2]
for i in range(0, 3):
for j in range(0, 3):
if (self.current_state[i][j] == '.'):
return None
return '.'
def max(self):
maxv = -2
px = None
py = None
result = self.is_end()
if result == 'X':
return (-1, 0, 0)
elif result == 'O':
return (1, 0, 0)
elif result == '.':
return (0, 0, 0)
def min(self):
minv = 2
qx = None
qy = None
result = self.is_end()
if result == 'X':
return (-1, 0, 0)
elif result == 'O':
return (1, 0, 0)
elif result == '.':
return (0, 0, 0)
for i in range(0, 3):
for j in range(0, 3):
if self.current_state[i][j] == '.':
self.current_state[i][j] = 'X'
(m, max_i, max_j) = self.max()
if m < minv:
minv = m
qx = i
qy = j
self.current_state[i][j] = '.'
def play(self):
name1 = input("Enter name of player 1: ")
name2 = input("Enter name of player 2: ")
while True:
self.draw_board()
self.result = self.is_end()
self.initialize_game()
return
if self.player_turn == 'X':
while True:
print(name1,"turn")
start = time.time()
(m, qx, qy) = self.min()
end = time.time()
print('Evaluation time: {}s'.format(round(end - start, 7)))
print('Recommended move: X = {}, Y = {}'.format(qx, qy))
if self.is_valid(px, py):
self.current_state[px][py] = 'X'
self.player_turn = 'O'
break
else:
print('The move is not valid! Try again.')
else:
while True:
print(name2,'turn')
(m, qx, qy) = self.max()
px = int(input('Insert the X coordinate: '))
py = int(input('Insert the Y coordinate: '))
if self.is_valid(px, py):
self.current_state[px][py] = 'O'
self.player_turn = 'X'
break
else:
print('The move is not valid! Try again.')
def main():
g = Game()
g.play()
if __name__ == "__main__":
main()
Alpha Beta
import time
class Game:
def __init__(self):
self.initialize_game()
def initialize_game(self):
self.current_state = [['.','.','.'],
['.','.','.'],
['.','.','.']]
def draw_board(self):
for i in range(0, 3):
for j in range(0, 3):
print('{}|'.format(self.current_state[i][j]), end=" ")
print()
print()
# Checks if the game has ended and returns the winner in each case
def is_end(self):
# Vertical win
for i in range(0, 3):
if (self.current_state[0][i] != '.' and
self.current_state[0][i] == self.current_state[1][i] and
self.current_state[1][i] == self.current_state[2][i]):
return self.current_state[0][i]
# Horizontal win
for i in range(0, 3):
if (self.current_state[i] == ['X', 'X', 'X']):
return 'X'
elif (self.current_state[i] == ['O', 'O', 'O']):
return 'O'
# Main diagonal win
if (self.current_state[0][0] != '.' and
self.current_state[0][0] == self.current_state[1][1] and
self.current_state[0][0] == self.current_state[2][2]):
return self.current_state[0][0]
# It's a tie!
return '.'
result = self.is_end()
if result == 'X':
return (-1, 0, 0)
elif result == 'O':
return (1, 0, 0)
elif result == '.':
return (0, 0, 0)
# Next two ifs in Max and Min are the only difference between
regular algorithm and minimax
if maxv >= beta:
return (maxv, px, py)
minv = 2
qx = None
qy = None
result = self.is_end()
if result == 'X':
return (-1, 0, 0)
elif result == 'O':
return (1, 0, 0)
elif result == '.':
return (0, 0, 0)
def play_alpha_beta(self):
check = 0
check = input('Press 0 to play against AI and 1 to play against another player:
')
while True:
self.draw_board()
self.result = self.is_end()
if self.result != None:
if self.result == 'X':
print('The winner is X!')
elif self.result == 'O':
print('The winner is O!')
elif self.result == '.':
print("It's a tie!")
self.initialize_game()
return
if self.player_turn == 'X':
while True:
start = time.time()
(m, qx, qy) = self.min_alpha_beta(-2, 2)
end = time.time()
print('Evaluation time: {}s'.format(round(end - start, 7)))
print('Recommended move: X = {}, Y = {}'.format(qx, qy))
qx = px
qy = py
if self.is_valid(px, py):
self.current_state[px][py] = 'X'
self.player_turn = 'O'
break
else:
print('The move is not valid! Try again.')
else:
if(check == '0'):
(m, px, py) = self.max_alpha_beta(-2, 2)
self.current_state[px][py] = 'O'
self.player_turn = 'X'
elif(check =='1'):
while True:
(m, qx, qy) = self.max_alpha_beta(-2, 2)
qx = px
qy = py
if self.is_valid(px, py):
self.current_state[px][py] = 'O'
self.player_turn = 'X'
break
else:
print('The move is not valid! Try again.')
def main():
g = Game()
g.play_alpha_beta()
if __name__ == "__main__":
main()
Result/Output:
MinMax
Alpha Beta
Task # 2:
Implementation of Tic Tac Toe game in GUI using TKinter by using MiniMax and Alpha-Beta pruning
algorithms.
Procedure/Program:
size_of_board = 600
symbol_size = (size_of_board / 3 - size_of_board / 8) / 2
symbol_thickness = 20
symbol_X_color = '#EE4035'
symbol_O_color = '#0492CF'
Green_color = '#7BC043'
class Tic_Tac_Toe():
# ------------------------------------------------------------------
# Initialization Functions:
# ------------------------------------------------------------------
def __init__(self):
self.window = Tk()
self.window.title('Tic-Tac-Toe')
self.canvas = Canvas(self.window, width=size_of_board, height=size_of_board)
self.canvas.pack()
# Input from user in form of clicks
self.window.bind('<Button-1>', self.click)
self.initialize_board()
self.player_X_turns = True
self.board_status = np.zeros(shape=(3, 3))
self.player_X_starts = True
self.reset_board = False
self.gameover = False
self.tie = False
self.X_wins = False
self.O_wins = False
self.X_score = 0
self.O_score = 0
self.tie_score = 0
def mainloop(self):
self.window.mainloop()
def initialize_board(self):
for i in range(2):
self.canvas.create_line((i + 1) * size_of_board / 3, 0, (i + 1) *
size_of_board / 3, size_of_board)
for i in range(2):
self.canvas.create_line(0, (i + 1) * size_of_board / 3, size_of_board, (i +
1) * size_of_board / 3)
def play_again(self):
self.initialize_board()
self.player_X_starts = not self.player_X_starts
self.player_X_turns = self.player_X_starts
self.board_status = np.zeros(shape=(3, 3))
# ------------------------------------------------------------------
# Drawing Functions:
# The modules required to draw required game based object on canvas
# ------------------------------------------------------------------
def display_gameover(self):
if self.X_wins:
self.X_score += 1
text = 'Winner: Player 1 (X)'
color = symbol_X_color
elif self.O_wins:
self.O_score += 1
text = 'Winner: Player 2 (O)'
color = symbol_O_color
else:
self.tie_score += 1
text = 'Its a tie'
color = 'gray'
self.canvas.delete("all")
self.canvas.create_text(size_of_board / 2, size_of_board / 3, font="cmr 60
bold", fill=color, text=text)
# ------------------------------------------------------------------
# Logical Functions:
# The modules required to carry out game logic
# ------------------------------------------------------------------
# Three in a row
for i in range(3):
if self.board_status[i][0] == self.board_status[i][1] ==
self.board_status[i][2] == player:
return True
if self.board_status[0][i] == self.board_status[1][i] ==
self.board_status[2][i] == player:
return True
# Diagonals
if self.board_status[0][0] == self.board_status[1][1] == self.board_status[2]
[2] == player:
return True
return False
def is_tie(self):
r, c = np.where(self.board_status == 0)
tie = False
if len(r) == 0:
tie = True
return tie
def is_gameover(self):
# Either someone wins or all grid occupied
self.X_wins = self.is_winner('X')
if not self.X_wins:
self.O_wins = self.is_winner('O')
if not self.O_wins:
self.tie = self.is_tie()
if self.X_wins:
print('X wins')
if self.O_wins:
print('O wins')
if self.tie:
print('Its a tie')
return gameover
if not self.reset_board:
if self.player_X_turns:
if not self.is_grid_occupied(logical_position):
self.draw_X(logical_position)
self.board_status[logical_position[0]][logical_position[1]] = -1
self.player_X_turns = not self.player_X_turns
else:
if not self.is_grid_occupied(logical_position):
self.draw_O(logical_position)
self.board_status[logical_position[0]][logical_position[1]] = 1
self.player_X_turns = not self.player_X_turns
# Check if game is concluded
if self.is_gameover():
self.display_gameover()
# print('Done')
else: # Play Again
self.canvas.delete("all")
self.play_again()
self.reset_board = False
game_instance = Tic_Tac_Toe()
game_instance.mainloop()
Result/Output:
Analysis/Conclusion: