Python is an interpreted, object-oriented programming language.
In this part, I have gone through some basics of python, game theory, and have created tic tac toe game
Simple, Complex, and Compound Sentences Exercises.pdf
Artificial intelligence - python
1. i) Objective : To learn about Basic Python and Game Development with AI.
ii) Introduction on Anaconda and Spyder IDE :
Anaconda :
Anaconda is a new distribution of the Python and R data science package. It was
formerly known as Continuum Analytics. Anaconda is used for scientific computing, data
science, statistical analysis, and machine learning. Anaconda provides conda as the package
manager whereas Python language provides pip as the package manager. Python pip allows
installing python dependencies.
Python packages :
For scientific computing and computational modelling, we need additional libraries
(so called packages) that are not part of the Python standard library. These allow us, for
example, to create plots, operate on matricies, and use specialised numerical methods, The
packages we generally need are -
numpy (NUMeric Python): matrices and linear algebra
scipy (SCIentific Python): many numerical routines
matplotlib: (PLOTting LIBrary) creating plots of data
sympy (SYMbolic Python): symbolic computation
pytest (Python TESTing): a code testing framework
Spyder IDE :
Spyder is a powerful scientific environment written in Python, for Python, and
designed by and for scientists, engineers and data analysts. It offers a unique combination of
the advanced editing, analysis, debugging, and profiling functionality. Spyder can also be
used as a PyQt5 extension library, allowing developers to build upon its functionality. The
name SPYDER derives from "Scientific PYthon Development EnviRonment" (SPYDER).
2. provision of the IPython (Qt) console as an interactive prompt, which can display plots
inline
ability to execute snippets of code from the editor in the console
continuous parsing of files in editor, and provision of visual warnings about potential
errors
step-by-step execution
variable explorer
Running the tests with Spyder :
1. Start Spyder
2. Download the file http://www.soton.ac.uk/~fangohr/blog/code/python/soton-test-python-
installation.py
3. Open the file in Spyder via File -> Open
4. The execute the file via Run -> Run.
PIP :
PIP is a recursive acronym that stands for “PIP Installs Packages” or “Preferred Installer
Program, used to install and manage software packages written in Python. It stands
for “Preferred Installer Program” or “PIP Installs Packages.” PIP for Python is a utility to
manage PyPI package installations from the command line.
How to Install PIP on Windows?
1. Download the get-pip.py installer script. If you’re on Python 3.2, you’ll need this version
of get-pip.py instead.
2. Open the Command Prompt and navigate to the get-pip.py file.
3. Run the following command: python get-pip.py
3. iii) Python basic Syntax :
To Print :
Indentation Uses:
To define an integer :
To define a floating point number :
Simple operators Using numbers and strings :
iv) Python Basic Problems :
Calculate the lengthof a string :
4. Sum all the items in a list :
Find the Max of three numbers (Using Function) :
V) AI in Game Theory :
In the context of artificial intelligence(AI) and deep learning systems, game theory is
essential to enable some of the key capabilities required in multi-agent environments in
which different AI programs need to interact or compete in order to accomplish a goal. Game
Theory and Artificial Intelligence are two mature areas of research, originating from similar
roots, which have taken different research directions in the last 50 years. AI is a way to
think and model software systems rather than a specific technique. From a conceptual
5. standpoint, there are several aspects of game theory that could help better understand AI
systems. Let’s explore a few of those concepts.
AI systems that could be improved using game theory require more than one participant which
narrows the field quite a bit. For instance, a sale forecast optimization AI systems such as
Salesforce Einstein is not an ideal candidate for applying game theory principles. However, in
a multi-participant environment, game theory can be incredibly efficient. In those settings,
game theory can serve two fundamental roles.
Participant Design: Game theory can be used to optimize the decision of a participant in order
to obtain the maximum utility.
Mechanism Design: Inverse game theory focus on designing a game for a group of intelligent
participant. Auctions are a classic example of mechanism design.
vi) Tic - Tac - Toe Program with full description :
Tic-tac-toe is a simple, two-player game which, if played optimally by both players, will
always result in a tie. The game is also called noughts and crosses or Xs and Os. A relatively
simple game usually played on a grid of 3 x 3 squares. Tic-tac-toe can be made significantly
more complex by increasing the size of the board to 4 x 4, 5 x 5, or even up to a 20 x 20 grid.
6. History of Tic Tac Toe :
An early variation of the game was played in the Roman Empire, around the 1st century
B.C. It was called terni lapilli, which means "three pebbles at a time." The game's grid
markings have been found chalked all over Roman ruins.
Gameplay :
The goal of tic-tac-toe is to be the 1st one to get three in a row on a 3 x 3 grid, or four in
a row in a 4 x 4 grid.
"X" always goes first. Players alternate placing Xs and Os on the board until either one
player has three in a row, horizontally, vertically, or diagonally; or all nine squares are
filled.
If a player is able to draw three of their Xs or three of their Os in a row, then that player
wins.
If all nine squares are filled and neither player has three in a row, the game is a draw.
Functions :
def insertBoard(letter, pos):
pass
def spaceIsFree(pos):
pass
def isWinner(bo, le):
pass
7. def playerMove():
pass
def selectRandom(li):
pass
def compMove():
pass
def isBoardFull(board):
pass
def printBoard():
pass
def main():
pass
Creating a Board :
We will be using a grid system to represent our board. To do this in python we will
create a list called board that will start off with 10 empty values. So to make our
lives easier we are going make the first value of our list an empty string. This way
when we index elements in our list we can use 1-9 not 0-8.
board = [' ' for x in range(10)] # This should be the first line in your program
# board is now: [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
8. insertLetter()
This function is going to take two parameters: letter & pos. It is simply going to
insert the given letter at the given position.
def insertLetter(letter, pos):
board[pos] = letter
spaceIsFree(pos)
This function will simply tell us if the given space is free. Meaning it does not
already contain a letter. It has one parameter, pos, which will be an integer from 1 -9.
def spaceIsFree(pos):
return board[pos] == ' '
# This function will return a True or False value
printBoard(board) :
This function takes the board as a parameter and will display it to the console.
def printBoard(board):
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
9. print(' | |')
print('-----------')
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
isWinner() :
This function will tell us if the given letter has won based on the current board. It
has two parameters: bo(board) & le(letter). The letter must be a “X” or an “O”. We
will simply check each possible winning line on the board and see if it is populated
by the given letter.
def isWinner(bo, le):
# Given a board and a player’s letter, this function returns True if that player has
won.
# We use bo instead of board and le instead of letter so we don’t have to type as m
uch.
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
10. main() :
This function is what we will call to start the game.
def main():
#Main game loop
print('Welcome to Tic Tac Toe, to win complete a straight line of your letter (Dia
gonal, Horizontal, Vertical). The board has positions 1-9 starting at the top left.')
printBoard()
while not(isBoardFull(board)):
if not(isWinner(board, 'O')):
playerMove()
printBoard()
else:
print('O's win this time...')
break
if not(isWinner(board, 'X')):
move = compMove()
if move == 0:
print('Game is a Tie! No more spaces left to move.')
else:
insertBoard('O', move)
print('Computer placed an 'O' in position', move, ':')
printBoard()
else:
11. print('X's win, good job!')
break
if isBoardFull(board):
print('Game is a tie! No more spaces left to move.')
isBoardFull() :
This function will return True if the board is full and False if it is not.
def isBoardFull(board):
if board.count(' ') > 1: # Since we always have one blank element in board we mu
st use > 1
return False
else:
return True
playerMove() :
In this function we will be asking the user to input a move and validating it.
def playerMove():
run = True
while run: # Keep looping until we get a valid move
move = input('Please select a position to place an 'X' (1-9): ')
try:
move = int(move)
if move > 0 and move < 10: # makes sure we type in a number between 1-9
12. if spaceIsFree(move): # check if the move we choose is valid (no other let
ter is there already)
run = False
insertBoard('X', move)
else:
print('This postion is already occupied!')
else:
print('Please type a number within the range!')
except:
print('Please type a number!')
compMove() :
Now time for the AI! This function will be responsible for making the computers
move. It will examine the board and determine which move is the best to make.
1. If there is a winning move take it.
2. If the player has a possible winning move on their next turn move into that
position.
3. Take any one of the corners. If more than one is available randomly decide.
4. Take the center position.
5. Take one of the edges. If more than one is available randomly decide.
6. If no move is possible the game is a tie.
def compMove():
possibleMoves = [x for x, letter in enumerate(board) if letter == ' ' and x != 0] #
Create a list of possible moves
move = 0
13. #Check for possible winning move to take or to block opponents winning move
for let in ['O','X']:
for i in possibleMoves:
boardCopy = board[:]
boardCopy[i] = let
if isWinner(boardCopy, let):
move = i
return move
#Try to take one of the corners
cornersOpen = []
for i in possibleMoves:
if i in [1,3,7,9]:
cornersOpen.append(i)
if len(cornersOpen) > 0:
move = selectRandom(cornersOpen)
return move
#Try to take the center
if 5 in possibleMoves:
move = 5
return move
#Take any edge
edgesOpen = []
for i in possibleMoves:
if i in [2,4,6,8]:
edgesOpen.append(i)
14. if len(edgesOpen) > 0:
move = selectRandom(edgesOpen)
return move
selectRandom() :
This function will randomly decide on a move to take given a list of possible
positions.
def selectRandom(li):
import random
ln = len(li)
r = random.randrange(0, ln)
return li[r]
Starting the Game:
If we just wanted to run the game once all we would have to do is call main.
while True:
answer = input('Do you want to play again? (Y/N)')
if answer.lower() == 'y' or answer.lower == 'yes':
board = [' ' for x in range(10)]
print('-----------------------------------')
main()
else:
break
15. Vii) Discussion :
Python has a simple syntax similar to the English language where as other languages
use punctuation, and it has fewer syntactical constructions than other languages. Python has
syntax that allows developers to write programs with fewer lines than some other
programming languages. Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be very fast.
Viii) Conclusion :
AI is a way to think and model software systems rather than a specific technique. A
task can be gamified and improved using AI techniques. Building bridges for the gap
between the technology and human. We concentrate on basic issues in representation,
reasoning, and learning, and discuss work that lies in the intersection of Artificial
Intelligence.AI systems that could be improved using game theory, there are several aspects
of game theory that could help better understand AI systems.
ix) References :
https://www.tutorialspoint.com/execute_python_online.php
https://www.southampton.ac.uk/~fangohr/blog/installation-of-python-spyder-numpy-sympy-
scipy-pytest-matplotlib-via-anaconda.html
https://www.makeuseof.com/tag/install-pip-for-python/