You are on page 1of 9

Course: AI Lab Part 2: Game playing

Lab 4: Play game based on Function cost

Name: Nguyễn Đức Phi Hồng


ID: ITITIU17022
Introduction to artificial intelligent

Tutorial:
Videos:
In Python:
Tictactoe: https://www.youtube.com/watch?v=BHh654_7Cmw

Coding:
In Python: 1) https://repl.it/@aaron_bernath/PythonTicTacToeApp
2) Sample codes (by Prof. Tho):
Procedures
1. initial code to play Tictactoe (play auto with random state)
Coding

Result (play gaming)


Course: AI Lab Part 2: Game playing

2. modify code to implement the next play based on the function cost.

TictacToe.py
# -*- coding: utf-8 -*-

class Board:
'''Class allowing to play Tic-Tac-Toe. It looks quite long but illustrate the
classical behavior of a game, giving methods you can find in some other games (such
as chess for example)'''
_X = 'X'
_O = 'O'
_E = '.' # empty

def __init__(self):
self._nextPlayer = self._X

self._board = []
for x in range(3):
self._board.append([self._E] * 3)

self._alignments = []
for x in range(3):
a = []
amirror = []
for y in range(3):
a.append((x, y))
amirror.append((y, x))
self._alignments.append(a)
self._alignments.append(amirror)
self._alignments.append([(0, 0), (1, 1), (2, 2)])
Course: AI Lab Part 2: Game playing

self._alignments.append([(2, 0), (1, 1), (0, 2)])

self._stack = [] # Used to keep track of push/pop moves

def _get_an_alignment(self):
for a in self._alignments:
if (self._board[a[0][0]][a[0][1]] != self._E) and (self._board[a[0][0]]
[a[0][1]] == self._board[a[1][0]][a[1][1]]) and (self._board[a[0][0]][a[0][1]] ==
self._board[a[2][0]][a[2][1]]):
return self._board[a[0][0]][a[0][1]]
return None

def _has_an_alignment(self):
return self._get_an_alignment() is not None

def _at_least_one_empty_cell(self):
for x in range(3):
for y in range(3):
if self._board[x][y] == self._E:
return True
return False

def is_game_over(self):
'''Test if the game is over'''
if self._has_an_alignment():
return True
if self._at_least_one_empty_cell():
return False
return True

def result(self):
'''Return the winner of the game'''
return self._get_an_alignment()

def push(self, move):


'''Allows to push a move to be able to unplay it later.'''
[player, x, y] = move
assert player == self._nextPlayer
self._stack.append(move)
self._board[x][y] = player
if self._nextPlayer == self._X:
self._nextPlayer = self._O
else:
self._nextPlayer = self._X

def pop(self):
'''Pop a move previously played. Allows to put back the board
in the same state as before playing.'''
move = self._stack.pop()
[player, x, y] = move
self._nextPlayer = player
self._board[x][y] = self._E

def legal_moves(self):
'''An important function : it allows to return all the possible moves
Course: AI Lab Part 2: Game playing

for the current board'''


moves = []
for x in range(3):
for y in range(3):
if self._board[x][y] == self._E:
moves.append([self._nextPlayer, x, y])
return moves

def _piece2str(self, c):


if c == self._O:
return 'O'
elif c == self._X:
return 'X'
else:
return '.'

def __str__(self):
toreturn = ""
for l in self._board:
for c in l:
toreturn += self._piece2str(c)
toreturn += "\n"
toreturn += "Next player: " + \
("X" if self._nextPlayer == self._X else "O") + "\n"
return toreturn

def moves_base_on_function_cost(self):
legal_moves = []
wining_moves = []
agaist_losing_move = []
for x in range(3):
for y in range(3):
if (self._board[x][y] == self._E):
legal_moves.append([self._nextPlayer, x, y])

# Vertical
cost = 0
for i in range(3):
if (self._board[i][y] == self._E):
continue
elif (self._board[i][y] == self._nextPlayer):
cost = cost + 1
elif (self._board[i][y] != self._nextPlayer):
cost = cost - 1

if cost == 2:
print("Add wining vertical")
wining_moves.append([self._nextPlayer, x, y])
if (cost == -2):
print("Add lossing vertical")
agaist_losing_move.append([self._nextPlayer, x, y])

# Horizontal
cost = 0
for i in range(3):
Course: AI Lab Part 2: Game playing

if (self._board[x][i] == self._E):
continue
elif (self._board[x][i] == self._nextPlayer):
cost = cost + 1
elif (self._board[x][i] != self._nextPlayer):
cost = cost - 1

if cost == 2:
print("Add wining horizzontal")
wining_moves.append([self._nextPlayer, x, y])
if (cost == -2):
print("Add lossing horizontal")
agaist_losing_move.append([self._nextPlayer, x, y])

# Left Diagonal
cost = 0
if (x == y):

if (self._board[0][0] == self._nextPlayer):
cost = cost + 1
if (self._board[0][0] != self._nextPlayer and self._board[0]
[0] != self._E):
cost = cost - 1

if (self._board[1][1] == self._nextPlayer):
cost = cost + 1
if (self._board[1][1] != self._nextPlayer and self._board[1]
[1] != self._E):
cost = cost - 1

if (self._board[2][2] == self._nextPlayer):
cost = cost + 1
if (self._board[2][2] != self._nextPlayer and self._board[2]
[2] != self._E):
cost = cost - 1

if cost == 2:
print("Add wining left diagonal")
wining_moves.append([self._nextPlayer, x, y])
if (cost == -2):
print("Add losing left diagonal")
agaist_losing_move.append([self._nextPlayer, x, y])

# Right Diagonal
cost = 0
if (x + y == 2):

if (self._board[2][0] == self._nextPlayer):
cost = cost + 1
if (self._board[2][0] != self._nextPlayer and self._board[2]
[0] != self._E):
cost = cost - 1

if (self._board[1][1] == self._nextPlayer):
cost = cost + 1
Course: AI Lab Part 2: Game playing

if (self._board[1][1] != self._nextPlayer and self._board[1]


[1] != self._E):
cost = cost - 1

if (self._board[0][2] == self._nextPlayer):
cost = cost + 1
if (self._board[0][2] != self._nextPlayer and self._board[0]
[2] != self._E):
cost = cost - 1

if cost == 2:
print("Add wining right diagonal")
wining_moves.append([self._nextPlayer, x, y])
if (cost == -2):
print("Add losing right diagonal")
agaist_losing_move.append([self._nextPlayer, x, y])
print("Wining Choices", end=" ")
print(wining_moves)
print("Against Losing Choices", end=" ")
print(agaist_losing_move)
print("Number of Legal Choices", end=" ")
print(len(legal_moves))

if len(wining_moves) > 0:
return wining_moves

if len(agaist_losing_move) > 0:
return agaist_losing_move

return legal_moves

__repr__ = __str__
Starter-tictactoe.py
# -*- coding: utf-8 -*-

import time
import Tictactoe
from random import randint, choice

def RandomMove(b):
'''Return a random move from the list of possible moves'''
return choice(b.legal_moves())

def FuntionCostMove(b):
'''Return a move base on function cost'''
return choice(b.moves_base_on_function_cost())

def deroulementRandom(b):
'''Play the Tic-Tac-Toe game randomly.'''
print("----------")
print(b)
if b.is_game_over():
Course: AI Lab Part 2: Game playing

res = getresult(b)
if res == 1:
print("Victory of X")
elif res == -1:
print("Victory of O")
else:
print("Draw")
return
# b.push(RandomMove(b))
b.push(FuntionCostMove(b))
deroulementRandom(b)
b.pop()

def getresult(b):
'''Function to evaluate the victory (or not) as X. Return 1 for victory, 0
for draw and -1 for lose. '''
if b.result() == b._X:
return 1
elif b.result() == b._O:
return -1
else:
return 0

if __name__ == '__main__':
board = Tictactoe.Board()
print(board)

# RandomGame
deroulementRandom(board)

print("After the match, every move is undone (thanks to pop()): we get back to the
initial board :")
print(board)

Result:
Course: AI Lab Part 2: Game playing
Course: AI Lab Part 2: Game playing

You might also like