SlideShare a Scribd company logo
1 of 16
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).
 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
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 :
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
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.
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
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: [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
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])
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
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:
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
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
#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)
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
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/
https://www.learnpython.org/en/Variables_and_Types
https://techwithtim.net/tutorials/python-programming/tic-tac-toe-tutorial/
https://medium.com/@jrodthoughts/game-theory-and-artificial-intelligence-ee8a6b6eff54
https://www.programiz.com/python-programming/methods/list/index
https://www.thesprucecrafts.com/tic-tac-toe-game-rules-412170

More Related Content

What's hot

What's hot (15)

Teeing Up Python - Code Golf
Teeing Up Python - Code GolfTeeing Up Python - Code Golf
Teeing Up Python - Code Golf
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Tic tac toe on c++ project
Tic tac toe on c++ projectTic tac toe on c++ project
Tic tac toe on c++ project
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
 
The Error of Our Ways
The Error of Our WaysThe Error of Our Ways
The Error of Our Ways
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 
Python Training v2
Python Training v2Python Training v2
Python Training v2
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data Types
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basics
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
Tic tac toe game with graphics presentation
Tic  tac  toe game with graphics presentationTic  tac  toe game with graphics presentation
Tic tac toe game with graphics presentation
 
Tic Tac Toe
Tic Tac ToeTic Tac Toe
Tic Tac Toe
 
Python language data types
Python language data typesPython language data types
Python language data types
 

Similar to Artificial intelligence - python

#include iostream#include fstream#include Opening.h.docx
#include iostream#include fstream#include Opening.h.docx#include iostream#include fstream#include Opening.h.docx
#include iostream#include fstream#include Opening.h.docx
adkinspaige22
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
Yashpatel821746
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
jovannyflex
 
Objectives Create a Java program using programming fundamentals (fi.docx
Objectives Create a Java program using programming fundamentals (fi.docxObjectives Create a Java program using programming fundamentals (fi.docx
Objectives Create a Java program using programming fundamentals (fi.docx
amit657720
 

Similar to Artificial intelligence - python (20)

#include iostream#include fstream#include Opening.h.docx
#include iostream#include fstream#include Opening.h.docx#include iostream#include fstream#include Opening.h.docx
#include iostream#include fstream#include Opening.h.docx
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
 
Lecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptxLecture 5 – Computing with Numbers (Math Lib).pptx
Lecture 5 – Computing with Numbers (Math Lib).pptx
 
Python programming
Python  programmingPython  programming
Python programming
 
Python slide
Python slidePython slide
Python slide
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Python basic
Python basicPython basic
Python basic
 
Objectives Create a Java program using programming fundamentals (fi.docx
Objectives Create a Java program using programming fundamentals (fi.docxObjectives Create a Java program using programming fundamentals (fi.docx
Objectives Create a Java program using programming fundamentals (fi.docx
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 
Week3.pptx
Week3.pptxWeek3.pptx
Week3.pptx
 
Class 3: if/else
Class 3: if/elseClass 3: if/else
Class 3: if/else
 

More from Sunjid Hasan

More from Sunjid Hasan (10)

Software engineering( sms )
Software engineering( sms )Software engineering( sms )
Software engineering( sms )
 
System analysis design of Fire Service & Civil Defence
System analysis design of Fire Service & Civil DefenceSystem analysis design of Fire Service & Civil Defence
System analysis design of Fire Service & Civil Defence
 
Digital image processing recognition of bengali handwritten digits using co...
Digital image processing   recognition of bengali handwritten digits using co...Digital image processing   recognition of bengali handwritten digits using co...
Digital image processing recognition of bengali handwritten digits using co...
 
Artificial intelligence - Prolog
Artificial intelligence - Prolog Artificial intelligence - Prolog
Artificial intelligence - Prolog
 
Cover page sample
Cover page sampleCover page sample
Cover page sample
 
Compiler and symbol table
Compiler and symbol tableCompiler and symbol table
Compiler and symbol table
 
System analysis design of fire service and civil defence
System analysis design of fire service and civil defenceSystem analysis design of fire service and civil defence
System analysis design of fire service and civil defence
 
Online blood sharing application
Online blood  sharing applicationOnline blood  sharing application
Online blood sharing application
 
Messaging application
Messaging applicationMessaging application
Messaging application
 
Estimation for software
Estimation for softwareEstimation for software
Estimation for software
 

Recently uploaded

Recently uploaded (20)

Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
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/