TGViewer
PyCoders (پایتون) PyCoders (پایتون) @python_rd · 4.1K subscribers
Post #2040 550
✨ بازی دوز یا Tic Tac Toe نسخه هوش مصنوعی


در این نسخه از بازی یک هوش مصنوعی با الگوریتم minimax بازی می‌کنه و عملاً شکست‌ناپذیره🤌🏻


"""
Tic Tac Toe با هوش مصنوعی (Unbeatable AI)
Python 3.x
"""

def print_board(board):
"""Prints the board in a nice 3x3 grid."""
print()
print(f" {board[0]} | {board[1]} | {board[2]} ")
print("---+---+---")
print(f" {board[3]} | {board[4]} | {board[5]} ")
print("---+---+---")
print(f" {board[6]} | {board[7]} | {board[8]} ")
print()

def check_winner(board, player):
"""Returns True if player ('X' or 'O') has won."""
winning_combos = [
(0, 1, 2), (3, 4, 5), (6, 7, 8), # rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # cols
(0, 4, 8), (2, 4, 6) # diagonals
]
return any(board[a] == board[b] == board[c] == player for a, b, c in winning_combos)

def is_draw(board):
"""Returns True if all cells are filled and no winner."""
return all(cell in ["X", "O"] for cell in board)

def get_valid_move(board):
"""Asks the human player for a valid move (1-9)."""
while True:
move_str = input("شماره خانه (1 تا 9) را وارد کن: ")
if not move_str.isdigit():
print("❌ فقط عدد وارد کن.")
continue

move = int(move_str)
if move < 1 or move > 9:
print("❌ عدد باید بین 1 تا 9 باشد.")
continue

index = move - 1
if board[index] in ["X", "O"]:
print("❌ این خانه قبلاً پر شده. یکی دیگه انتخاب کن.")
continue

return index

def minimax(board, is_maximizing, ai_player, human_player):
"""Minimax algorithm: returns score from AI perspective."""
if check_winner(board, ai_player):
return 1
if check_winner(board, human_player):
return -1
if is_draw(board):
return 0

if is_maximizing:
best_score = -999
for i in range(9):
if board[i] not in ["X", "O"]:
backup = board[i]
board[i] = ai_player
score = minimax(board, False, ai_player, human_player)
board[i] = backup
if score > best_score:
best_score = score
return best_score
else:
best_score = 999
for i in range(9):
if board[i] not in ["X", "O"]:
backup = board[i]
board[i] = human_player
score = minimax(board, True, ai_player, human_player)
board[i] = backup
if score < best_score:
best_score = score
return best_score

def find_best_move(board, ai_player, human_player):
"""Finds the best move for AI using minimax."""
best_score = -999
best_move = None
for i in range(9):
if board[i] not in ["X", "O"]:
backup = board[i]
board[i] = ai_player
score = minimax(board, False, ai_player, human_player)
board[i] = backup
if score > best_score:
best_score = score
best_move = i
return best_move

def main():
print("🎮 بازی دوز با هوش مصنوعی (Tic Tac Toe + AI)")
print("این نسخه، هوش مصنوعی تقریباً بدون شکست داره 😉")
print("چینش خانه‌ها به شکل زیر است:")
demo_board = [str(i) for i in range(1, 10)]
print_board(demo_board)

# انتخاب علامت توسط کاربر
while True:
human_player = input("دوست داری X باشی یا O؟ (X/O): ").strip().upper()
if human_player in ["X", "O"]:
break
print("فقط X یا O وارد کن.")

ai_player = "O" if human_player == "X" else "X"
print(f"تو = {human_player} | هوش مصنوعی = {ai_player}")

board = [str(i) for i in range(1, 10)]

# اگر انسان O باشد، AI با X شروع می‌کند
current_player = "X"

while True:
print_board(board)
More from @python_rd
  1. Oct 17, 2026🔆 یادگیری پایتون با پروژه های ساده و جذاب 🔹 codeclubprojects.org/en-GB/python 🐍 @python…
  2. Oct 16, 2026🔆 یک سایت خوب پر از پادکست‌های مرتبط با زبان پایتون 🔹 talkpython.fm 🐍 @python_rd
  3. Oct 15, 2026🌐 خروجی این کد پایتون چیست؟ x = [1, 2, 3] y = x x += [4, 5] print(x) print(y) 🔹 گزینه‌ها…
  4. Oct 15, 2026🔆 آیا enumerate() بهتر از index-based loop است؟ 🔹 خیلی‌ها هنوز این شکلی می‌نویسند: items…
  5. Oct 15, 2026🔆 یک تله عجیب در پایتون: bool در واقع زیرکلاس int است 🔹 خیلی‌ها می‌دانند True == 1 و Fal…
  6. Oct 13, 2026کوییز پایتون 🔆 خروجی اجرای کد زیر چیست؟ t = (1, 2, [3, 4]) try: t[2] += [5] except TypeEr…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →