This article shares the python implementation of tic-tac-toe game for everyone, for your reference, the specific content is as follows
I took a python elective course on Friday night. I thought the teacher started with the basic grammar of python, but I didn’t expect it to start with turtle drawing. It happened to fill in some of the things I didn’t understand before. Someone’s talk is better than a book. a little.
I borrowed a python game programming book from the library before. After reading the first few chapters, I didn't read it much. I suddenly wanted to read it at night, and then I wrote a game following the tutorial. Finally, the Tic-Tac-Toe was born. In fact, the code is not very long, mainly because of ideas, which need to be considered thoroughly. After the code was written, I played tic-tac-toe with the computer for a long time, and I didn't win a round. It was really helpless, and it couldn't be compared.
Development environment: windows10 + pycharm (because input is required when playing chess, sublime doesn't know how to input, so pycharm is used)
There is only one package that needs to be used: random
For the game, the first thing to figure out is the flow of the game, what to do first and then what to do. Tic-tac-toe is relatively not a complicated game, so the process will not be explained. The first thing I do is to draw the chessboard, the computer and the player's pieces, who will place the pieces first, etc. The following is explained by code:
# The function of drawing chess board, passing in a list of chess pieces
def drawBoard(board):print(" "+ board[7]+" | "+ board[8]+" | "+ board[9])print("------------")print(" "+ board[4]+" | "+ board[5]+" | "+ board[6])print("------------")print(" "+ board[1]+" | "+ board[2]+" | "+ board[3])
# The player chooses the type of chess pieces they want to use
def inputPlayerLetter():
letter =''whilenot(letter =='X' or letter =='O'):print("Do you want to be X or O")
# Automatically convert lowercase to uppercase
letter =input().upper()
# If the player chooses X, O will be automatically assigned to the computer, and vice versa
if letter =='X':return['X','O']else:return['O','X']
# Here, 0 or 1 is randomly generated to indicate who will settle first
def whoGoesFirst():if random.randint(0,1)==0:return'computer'else:return'player'
# If the player chooses y or Y, the game restarts
def playAgain():print("Do you want to play again?(yes or no)")returninput().lower().startswith('y')
# Place the chess pieces on the board
# The board parameter is a list of stored chess pieces
# The letter parameter is the type of the chess piece
# move is to choose where to place the chess pieces
def makeMove(board, letter, move):
board[move]= letter
# Determine whether to win according to the Tic Tac Toe rules
def isWinner(bo, le):return((bo[7]== le and bo[8]== le and bo[9]== le)or(bo[4]== le and bo[5]== le and bo[6]== le)or(bo[1]== le and bo[2]== le and bo[3]== le)or(bo[7]== le and bo[4]== le and bo[1]== le)or(bo[8]== le and bo[5]== le and bo[2]== le)or(bo[9]== le and bo[6]== le and bo[3]== le)or(bo[7]== le and bo[5]== le and bo[3]== le)or(bo[9]== le and bo[5]== le and bo[1]== le))
# Back up the pieces already on the board,update at any time
def getBoardCopy(board):
dupeBoard =[]for i in board :
dupeBoard.append(i)return dupeBoard
# Determine whether the chessboard has any place to place
def isSpaceFree(board, move):return board[move]==' '
# Get the player's position
def getPlayerMove(board):
move =' '
# Determine whether the position of the move is correct and whether the board can still be placed
while move not in'1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,int(move)):print("What is your next move?(1-9)")
move =input()returnint(move)
# Find a place where you can drop off, mainly for computer use
def chooseRandomMoveFromList(board, moveList):
possibleMoves =[]for i in moveList :ifisSpaceFree(board, i):
possibleMoves.append(i)iflen(possibleMoves)!=0:return random.choice(possibleMoves)else:return None
The above code implements some simple functions, and then implements the part of the computer. After all, it is a computer, so it has to look less silly, so the following is equivalent to a small AI. The computer can judge on the backup copy. The result is to specify the position of the drop:
# Computer placement
def getComputerMove(board, computerLetter):
# Give the type of computer and player pieces on the board
if computerLetter =='X':
playerLetter ='O'else:
playerLetter ='X'for i inrange(1,10):
# Determine whether there is a place to place a piece in the backup board
copy =getBoardCopy(board)ifisSpaceFree(copy, i):
# If there is a place to settle,First place a piece on the backup board
makeMove(copy, computerLetter, i)
# Determine whether the computer can win after the position,And return to the position of the winning move
ifisWinner(copy, computerLetter):return i
for i inrange(1,10):
copy =getBoardCopy(board)ifisSpaceFree(copy, i):
# Simulate player moves on the backup board
makeMove(copy, playerLetter, i)
# If the next time the player makes a move, they can win,Returns the position of the player's place,Used to block players
ifisWinner(copy, playerLetter):return i
# Randomly place in the four corners
move =chooseRandomMoveFromList(board,[1,3,7,9])if move != None :return move
# If the corner is full,Then the drop is in the middle position 5.
ifisSpaceFree(board,5):return5
# If the corners and the middle are occupied,Random selection
returnchooseRandomMoveFromList(board,[2,4,6,8])
# Determine if the board is full
def isBoardFull(board):for i inrange(1,10):ifisSpaceFree(board, i):return False
return True
print("Welcome to Tictactoe !!!")while True :
# Initialize the board to be empty
theBoard =[' ']*10
# Choice of player and computer chess types
playerLetter, computerLetter =inputPlayerLetter()
# Priority decision
turn =whoGoesFirst()print('The '+ turn +' will go first')
# The game start flag,Becomes False when the game ends
gameIsPlaying = True
while gameIsPlaying :
# Player first
if turn =='player':drawBoard(theBoard)
# Get the player's chess position
move =getPlayerMove(theBoard)
# Pass the player's pieces to the corresponding position in the list
makeMove(theBoard, playerLetter, move)
# If the player wins,The flag becomes False
ifisWinner(theBoard, playerLetter):drawBoard(theBoard)print("You win !")
gameIsPlaying = False
# Otherwise, judge whether the board is full
else:ifisBoardFull(theBoard):drawBoard(theBoard)print("Tie")break
# If the board is not full,And the player has settled,Then it will fall into the computer next time
else:
turn ='computer'
# Computer first
else:
# The computer randomly selects the location
move =getComputerMove(theBoard, computerLetter)makeMove(theBoard, computerLetter, move)
# If the computer wins,The game is over
ifisWinner(theBoard, computerLetter):drawBoard(theBoard)print("You lose !")
gameIsPlaying = False
else:ifisBoardFull(theBoard):drawBoard(theBoard)print("Tie")breakelse:
turn ='player'
# The player did not start the game again,Out of the loop
if not playAgain():break
All the above codes realize the human-machine battle of Tic-Tac-Toe, which can be played after being integrated. Anyway, I have never won.
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts