Phần 19: Gaming – Phần 2 – Lập trình AI bằng Python

Phần 19: Gaming – Phần 2                        – Lập trình AI bằng Python

7. Tạo bot chơi Tic Tac Toe

Tic-Tac-Toe rất thân thuộc và là 1 trong các trò chơi được rất nhiều người yêu thích. Ta hãy thử tạo game này bằng cách sử dụng thư viện easyAI trong Python.
from easyAI import TwoPlayersGame, AI_Player, Negamax
from easyAI.Player import Human_Player
Kế thừa lớp từ lớp TwoPlayerRecreation để xử lý toàn bộ những hoạt động của game
class TicTacToe_game(TwoPlayersGame):
   def __init__(self, gamers):
Xác định game thủ và game thủ sẽ bắt đầu trò chơi
self.gamers = gamers
self.nplayer = 1
Xác định board :
self.board = [0] * 9
Hiện tại có những điều nhất định cần xác định như dưới đây:
Xác định những bước di chuyển có thể
def possible_moves(self):
   return [x + 1 for x, y in enumerate(self.board) if y == 0]
Xác định bước di chuyển của 1 game thủ
def make_move(self, transfer):
   self.board[int(move) - 1] = self.nplayer
Để tăng cường AI, hãy xác định thời điểm game thủ di chuyển :
def umake_move(self, transfer):
   self.board[int(move) - 1] = 0
Xác định điều kiện thua mà đối thủ có ba người trên 1 hàng :
def condition_for_lose(self):
   possible_combinations = [[1,2,3], [4,5,6], [7,8,9],
      [1,4,7], [2,5,8], [3,6,9], [1,5,9], [3,5,7]]
   return any([all([(self.board[z-1] == self.nopponent)
      for z together]) for mixture in possible_combinations])
Xác định kiểm tra kết thúc trò chơi
def is_over(self):
   return (self.possible_moves() == []) or self.condition_for_lose()
Hiển thị vị trí hiện giờ của game thủ trong game
def present(self):
   print('n'+'n'.be part of([' '.join([['.', 'O', 'X'][self.board[3*j + i]]
      for i in vary(3)]) for j in vary(3)]))
Tính điểm :
def scoring(self):
   return -100 if self.condition_for_lose() else 0
Xác định cách chính để xác định thuật toán và bắt đầu trò chơi :
if __name__ == "__main__":
   algo = Negamax(7)
   TicTacToe_game((*2*)).play()
Bạn sẽ có thể xem kết quả sau và lối chơi đơn giản của game này
. . .
. . .
. . .
Player 1 what do you play ? 1
Move #1: participant 1 performs 1 :
O . .
. . .
. . .
Move #2: participant 2 performs 5 :
O . .
. X .
121
. . .
Player 1 what do you play ? 3
Move #3: participant 1 performs 3 :
O . O
. X .
. . .
Move #4: participant 2 performs 2 :
O X O
. X .
. . .
Player 1 what do you play ? 4
Move #5: participant 1 performs 4 :
O X O
O X .
. . .
Move #6: participant 2 performs 8 :
O X O
O X .
. X .

admin

Leave a Reply

Your email address will not be published. Required fields are marked *